Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interesting behavior about ES6 array destructuring and swapping [duplicate]

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!

like image 841
Kevin Qian Avatar asked Mar 13 '26 16:03

Kevin Qian


2 Answers

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)
like image 99
Ori Drori Avatar answered Mar 15 '26 06:03

Ori Drori


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.

like image 39
Jonas Wilms Avatar answered Mar 15 '26 05:03

Jonas Wilms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!