Destructuring Assignment - Arrays Example: Why does this work?

Hi,

Can someone please explain why this works without using const:

let a = 8, b = 6;
// change code below this line
[a, b] = [b, a];

// change code above this line
console.log(a); // should be 6
console.log(b); // should be 8

I can’t get my head around it!

Thanks.

The variables have already been defined in the first line, so you couldn’t use const if you wanted to. The left side is just destructuring the array on the right side of the assignment operator. The first element gets assigned to variable b and the second element gets assigned to a.

Maybe the following would help:

let a = 8, b = 6;
// change code below this line
const [c, d] = [b, a];

// change code above this line
console.log(c); // should be 6
console.log(d); // should be 8

In the above example, we are creating new variables (c and d), but still destructuring an array which has two elements (the values of variable b and a respectively).

Got it - many thanks @RandellDawson