I was trying some things today and came across a behaviour I would like to understand.
var b = ({a = 1, b = 1, c = 1}) => a + b + c;
b(); // throws error.
But if it is defined like this
var b = ({a = 1, b = 1, c = 1} = 0) => a + b + c;
b() // returns 3
b([]) // returns 3
Shouldn’t this be an error? Did zero somehow become an object here? Is it somehow equivalent to the following?
var b = ({a = 1, b = 1, c = 1} = {}) => a + b + c; // this is possible I guess.
My question is not how regular destrcuturing and default params work, but only how this particular scenario is being evaluated.
Can some one explain this to me?
Destructuring is a JavaScript expression that allows us to extract data from arrays, objects, and maps and set them into new, distinct variables. Destructuring allows us to extract multiple properties, or items, from an array at a time.
Each destructured property can have a default value. The default value is used when the property is not present, or has value undefined . It is not used if the property has value null . The default value can be any expression.
In Arrays: In Arrays, values of corresponding elements get stored in the variables. Example 1: In order to give default values in arrays when applying the destructuring concept in arrays, we need to initialize values with some value. In this way the default values will be assigned to the variables.
Destructuring Assignment is a JavaScript expression that allows to unpack values from arrays, or properties from objects, into distinct variables data can be extracted from arrays, objects, nested objects and assigning to variables.
({a = 1, b = 1, c = 1} = something) => {}
just means that something
must be an object or can be converted to one, i.e. it can’t be null
or undefined
.1
So, in the case of 0
, it proceeds to grab the a
, b
and c
properties of 0
, i.e. (0).a
, (0).b
, (0).c
, all of which are undefined
, hence all of them default to 1
, their provided default value.
0
can of course be coerced to a Number
object. That’s why you can do (0).toString()
or {toString} = 0
. That’s exactly what happens here.
It’s generally not equivalent to using {}
as a default, since that would use an empty object’s properties (both own properties and the ones on the prototype chain), not the number’s properties.
1: The most reduced form of this “structural verification” is ({} = something)
. For destructuring onto arrays, it is ([] = something)
and it means that the something
must also be iterable. Those empty destructuring assignments, by the way, don’t create any variables, they just do the structure check.
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