Kevin Qian
Kevin Qian

Reputation: 2720

Interesting behavior about ES6 array destructuring and swapping

I just noticed that the following code, without immediately referencing one after let [one, two] = [1, 2], trying [one, two] = [two, one] would crash:

let [one, two, three] = [1, 2, 3]
[one, two] = [two, one] // CRASH! one is not defined
console.log(one, two)

However, simply adding a not-used one between the declaration and swapping suddenly allows the code, but incorrectly:

let [one, two, three] = [1, 2, 3]
one // inserted here
[one, two] = [two, one] // no longer crashes! but not actually swapping
console.log(one, two) // should be '2 1', but shows '1 2' instead

Whereas the below code gives the expected swapping effect

var a = 1;
var b = 3;

[a, b] = [b, a];
console.log(a); // 3
console.log(b); // 1

Can someone explain why such behavior exists? Thanks!

Upvotes: 2

Views: 800

Answers (2)

Jonas Wilms
Jonas Wilms

Reputation: 138267

Cause its parsed like this:

 let [one, two, three] = [1, 2, 3][one, two] = [one, two]

To make it work, always suround destructuring assignments with parens:

 let [one, two, three] = [1, 2, 3];
 ([one, two] = [two, one]);
 console.log(one, two);

And never ever trust ASI, there are some cases like this were it goes wrong.

Upvotes: 2

Ori Drori
Ori Drori

Reputation: 191976

Add a semicolon to the 1st line, because the interpreter assumes that lines 1 and 2 declarations happen together, and one (and two) is not defined yet:

let [one, two, three] = [1, 2, 3];
[one, two] = [two, one]
console.log(one, two)

Upvotes: 6

Related Questions