ES6: Use Destructuring Assignment to Assign Variables from Arrays

const [a, b] = [1, 2, 3, 4, 5, 6];

is like

const arr = [1, 2, 3, 4, 5, 6];

const a = arr[0];
const b = arr[1];

I get that it’s slightly confusing, the example doesn’t quite relate to what you’re doing. So instead think like

const arr = [1, 2, 3, 4, 5, 6];

let a = arr[0];
let b = arr[1];

Because they use let, you can now reassign those variables

a = 5
b = 'hello'

That’s fine - as you say, you wouldn’t be able to do that with const because a and b would not be reassignable.

So in the code here:

let a = 8, b = 6;
(() => {
  "use strict";
  [a, b] = [b, a];
})();

If we get rid of the stuff that’s just there to help with the tests:

let a = 8;
let b = 6;
[a, b] = [b, a];

You’ve already defined the variables a and b. The code is the same as doing:

let a = 8;
let b = 6;
// create something to hold onto a value while we swap:
let temp = a;
a = b;
b = temp;

You don’t put let before the [a, b] because a and b are already defined - that would be a reference error, as @moein says (but it has absolutely nothing to do with strict mode), but it would be a reference error because they have already defined a and b. eg you can’t do:

let a = 10;
// then
let a = 20;

Because you can only use let a once, you redefine like:

let a = 10;
// then
a = 20;

This is not correct, strict mode has nothing to do with it, that’s just there for the tests.

4 Likes