Search code examples
javascriptecmascript-6destructuring

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!


Solution

  • 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)