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!
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)
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.
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