javascriptecmascript-6syntaxdestructuring

ES6 Array destructuring weirdness


Can anyone explain, why the following happens with ES6 array destructuring?

let a, b, c
[a, b] = ['A', 'B']
[b, c] = ['BB', 'C']
console.log(`a=${a} b=${b} c=${c}`)

Expected: a=A b=BB c=C

Actual: a=BB b=C c=undefined


Solution

  • As others have said, you're missing semicolons. But…

    Can anyone explain?

    There are no semicolons automatically inserted between your lines to separate the "two" statements, because it is valid as a single statement. It is parsed (and evaluated) as

    let a = undefined, b = undefined, c = undefined;
    [a, b] = (['A', 'B']
    [(b, c)] = ['BB', 'C']);
    console.log(`a=${a} b=${b} c=${c}`);
    

    wherein

    If you want to omit semicolons and let them be automatically inserted where ever possible needed, you will need to put one at the start of every line that begins with (, [, /, +, - or `.