JavaScript Defaults for JavaScript

I can fully understand that ECMAScript 6 has created many features for working with functions such as arrow functions.

Since I am not very familiar with the new material when it comes to the default parameters for the function. How to interpret the differences between the following function definitions:

Function 1:

function m1({x = 0, y = 0} = {}) { return [x, y]; } 

Function 2:

 function m2({x, y} = { x: 0, y: 0 }) { return [x, y]; } 
+5
source share
2 answers

The difference is obvious when you try to pass something to your functions:

 m1({}) // [0, 0] m1({z: 1}) // [0, 0] m1({x: 1}) // [1, 0] m2({}) // [undefined, undefined] m2({z: 1}) // [undefined, undefined] m2({x: 1}) // [1, undefined] 

Your first syntax ( m1({x = 0, y = 0} = {}) ) has three functions:

  • First, it provides the first default argument to a function that is an empty object. If the first argument is not specified ( m1() ), then an empty default object is used (that is, it becomes m1({}) )
  • Secondly, your code extracts the x and y properties from this object.
  • If the value is undefined , it is assigned a default value of 0 .

m2({x, y} = { x: 0, y: 0 }) does something completely different:

  • First, it provides the first default parameter for a function that is the object {x: 0, y: 0} . If the first argument is not passed, this object is used. If any argument other than undefined passed, this value is used instead.
  • Secondly, the code extracts the x and y properties from this object. If they are undefined , this is what you get.

The first parameter (a parameter with a default value, destructured with more standard values) is almost certainly what you want. The second option means that your code does not have reasonable / useful default values ​​for the property if the arguments are passed.

+4
source

m1 provides default values ​​for x and y , while m2 simply destroys x and y from the provided object and provides only default values ​​if the object itself is not specified:

  • m1({}) will return [0, 0]
  • m2({}) will return [undefined, undefined]
  • Both m1() and m2() will return [0, 0]

  • m1({x: 10}) will return [10, 0]
  • m2({x: 10}) will return [10, undefined]

So, if m2 gets the object, it will destroy the available values ​​for the variables x and y . If any of them is missing, its undefined . Only if the entire object is absent does it provide a default object ( { x: 0, y: 0 } ) from which values ​​can be obtained.

m1 , however, provides default values ​​for both properties, even if they are missing. And if the entire object is missing, it will still provide these default values.

0
source

Source: https://habr.com/ru/post/1263921/


All Articles