logo

Array destructuring

It is important to note, even from the beginning, that in array destructuring, the value assigned to the variables depends on the order.

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

In the past we used:

const first = numbers[0];
const second = numbers[1];
const third = numbers[2];

By using destructuring, we create 3 variables by getting the items with an index 0, 1, 2 from the numbers array:

const [first, second, third] = numbers;
first; // 1
second; // 2
third; // 3

When needed, you can skip some items:

const colors = ["purple", "lightblue", "magenta", "lightgreen"];
const [firstColor, , , lastColor] = colors;
firstColor; // "purple"
lastColor; // "lightgreen"

A variable can be assigned a default value if the value unpacked from the array is undefined:

let x;
let y;
[x = 1, y = 7] = [0];
x; // 0
y; // 7

Given two variables, you can swap their values:

let num1 = 10;
let num2 = 20;

[num1, num2] = [num2, num1];
num1; // 20
num2; // 10

You can assign the rest of an array to a variable:

const [a, ...b] = [1, 2, 3, 4];
a; // 1
b; // [2, 3, 4]