madox2
madox2

Reputation: 51841

ES6 destructuring assignment - strange expression evaluation

Pointing to this question I found strange behaviour in es6 destructuring assignment.

var a = [1, 2, 3];
console.log([] = a); // Array [ 1, 2, 3 ]
console.log([x] = a); // Array [ 1, 2, 3 ]
console.log([x, y] = a); // Array [ 1, 2, 3 ]
console.log(x, y); // 1, 2

I would expect to see ouptut like:

Array [ ]
Array [ 1 ]
Array [ 1, 2 ] 

Can you explain this?

Upvotes: 1

Views: 134

Answers (1)

PSWai
PSWai

Reputation: 1188

It might be a bit difficult to digest, but this is the official documentation of assignment operators (The first part of 12.14.4 being specifically the = operator).

Notice step 8 that reads "return rval". It essentially means that a = b will returns b.

So the results are correct:

var a = [1, 2, 3];
console.log([] = a); // [] = a gives a, so print Array [ 1, 2, 3 ]
console.log([x] = a); // [x] = a gives a, so print Array [ 1, 2, 3 ]
console.log([x, y] = a); // [x, y] = a gives a, so print Array [ 1, 2, 3 ]
console.log(x, y); // x and y were destructed correctly, so print 1, 2

Upvotes: 2

Related Questions