const [a, b] = [1, 2]
// expected to be equal to
// const a = 1
// const b = 2
const [c, d] = [3, 4]
// expected to be equal to
// const c = 3
// const d = 4
[a, b] = [b, a]
// expected Assignment to constant variable error
console.log(a, b, c, d)
// => 1, 2, 2, 1
Can someone explain what is wrong with this code? What happened to variables c and d?
You're not using semi-colons and ASI doesn't always work the way you would like.
Your code is equivalent to this:
const [a, b] = [1, 2];
const [c, d] = [3, 4][a, b] = [b, a];
console.log(a, b, c, d);
[3, 4][a, b] in this case evaluates as [3,4][2] since the second comma is just the comma operator and b === 2. That makes the assignment equivalent to [3,4][2] = [b,a] which results in a temporary array [3,4,[2,1]] being created and the result of the assignment expression [2,1] is then assigned to [c,d].
Try adding semi-colons and you will get the expected results:
const [a, b] = [1, 2];
// expected to be equal to
// const a = 1
// const b = 2
const [c, d] = [3, 4];
// expected to be equal to
// const c = 3
// const d = 4
[a, b] = [b, a];
// expected Assignment to constant variable error
console.log(a, b, c, d);
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