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.
source share