Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array destructuring - unexpected behavior

Tags:

javascript

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?

like image 627
Konstantin Avatar asked Mar 05 '26 15:03

Konstantin


1 Answers

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);
like image 80
Paul Avatar answered Mar 08 '26 03:03

Paul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!