5

Javascript allows swapping of variables:

var x = 1
var y = 2

[x, y] = [y, x] // y = 1 , x = 2

And destructured assignment:

var a, b
[a, b] = [1, 2]

log(a) // 1
log(b) // 2

When using variable swapping in lieu with destructured assignment, trying to swap variables breaks down:

var a, b
[a, b] = [1, 2] // a = 1, b = 2

[a, b] = [b, a] // TypeError: Cannot set property '2' of undefined

Why is that?

3
  • It works in chrome(56.0.2924.87), what browser you are running? , are you using a transpiler or node ? Commented Mar 2, 2017 at 18:11
  • I don't get that error, but one thing I'd do is add a semicolon after the first assignment ([a, b] = [1, 2];). Commented Mar 2, 2017 at 18:11
  • I'm using Node 7.4.0. Commented Mar 2, 2017 at 18:13

1 Answer 1

10

If you decide to omit semicolons (no judgement, I prefer it that way too), don't forget to prefix lines beginning with array literals with ;. Occasionally, semicolon insertion does matter, because it might not occur when you want or expect it to.

var a, b
;[a, b] = [1, 2]

;[a, b] = [b, a]

console.log(a, b)

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you @gyre. Would you mind explaining why exactly the semicolons are needed in this case? Or give a pointer to a resource explaining it?
Basically, the JS engine sees this when you don't use semicolons: var a, b; [a, b] = [1, 2][a, b] = [b, a]. Some of the array literals are interpreted as property accesses, and the commas used to separate elements are interpreted as the comma operator instead.
For more information, I would suggest reading this section on ASI in Kyle Simpson's book You Don't Know JS.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.