Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why did ECMASCRIPT 6 reverse the sides for assignment when destructuring? [closed]

Why did ES6 decide that left-side assignment made more sense or was more useful for destructured assignments? Just on first look, it seems to make code more error prone, now that assignment can happen on both sides, depending on situation.

let obj = { first: 'Jane', last: 'Doe' };
let { first: f, last: l } = obj;
// f = 'Jane'
// l = 'Doe'

f and l are both seemingly being defined on the left, using values from a combination of the var names on the left and values of those vars from the right.

Given that the rationale for this sytax is the keep it the same as object declaration syntax, why would ECMA not instead have used:

let { f: first, l: last } = obj;
like image 668
BrianFreud Avatar asked Nov 19 '16 22:11

BrianFreud


People also ask

Does Destructuring copy reference?

It looks like destructuring feature works by reference and it's not copying the value. So when you work with destructuring bear in mind to pay a lot of attention when you change a value inside your destructured Objects and Arrays!

What is the difference between Destructuring and rest operator?

Destructuring is used to create varibles from array items or object properties. Spread syntax is used to unpack iterables such as arrays, objects, and function calls. Rest parameter syntax will create an array from an indefinite number of values.

How do you Destructure an object in ES6?

When destructuring the objects, we use keys as the name of the variable. The variable name must match the property (or keys) name of the object. If it does not match, then it receives an undefined value. This is how JavaScript knows which property of the object we want to assign.

What are default values in Destructuring assignment in JavaScript?

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.


1 Answers

Because it is supposed to keep the object literal syntax: the property name comes before the colon. The syntax is supposed to nest, and that wouldn't work properly if the target was on the left side:

let {propName: [arrayElement, ...moreElements], otherName: {nestedProp: targetName}} = obj;

In your approach, it would be

let {[arrayElement, ...moreElements]: propName, {targetName = nestedProp}: otherName} = obj;

where the colon doesn't make any sense.

like image 180
Bergi Avatar answered Oct 05 '22 02:10

Bergi