I can fully understand ECMAScript 6 has created a lot of potential way of handling with functions such as arrow functions.
Since I'm not very familiar with the new stuff, when talking about default parameters for a function. How to interpret the differences between the following way of defining functions:
Function 1:
function m1({x = 0, y = 0} = {}) {
return [x, y];
}
Function 2:
function m2({x, y} = { x: 0, y: 0 }) {
return [x, y];
}
The difference is clear when you try passing 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} = {})) does three things:
m1()) then the default empty object is used (i.e. it becomes m1({}))x and y properties from that object.undefined, it is given a default value 0.m2({x, y} = { x: 0, y: 0 }) does something quite different:
{x: 0, y: 0}. If no first argument is passed, that object is used. If any argument other than undefined is passed, that value is used instead.x and y properties from that object. If they are undefined, that's what you'll get.The first option (a parameter with a default value that is destructured with more default values) is almost certainly what you want. The second option means that your code does not have sensible/useful default values for the property if arguments are passed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With