Reputation: 41
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?
Upvotes: 3
Views: 196
Reputation: 141829
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);
Upvotes: 4
Reputation: 88
Instead of:
const [a, b] = [1, 2];
Try:
const a = 1, b = 2;
const c = 3, d = 4;
To swap the values, try something like:
var temp;
temp = a; a = b; b = temp;
Upvotes: -3
Reputation: 2947
It's basically a problem with not terminating commands properly with a semi-colon (;
). If you add them to the end of each command you will get the proper result.. and also run into the problem where you cannot reassign a
and b
as they're declared as const
.
Upvotes: 1