What is array destructuring

JavaScript

Array Destructuring

Imagine you have information stored in an array and you want to extract that information into separate variables.

Conventionally, this is achieved by referencing an element by its index in a standard assignment.

const cars = ['Ford', 'Toyota', 'Honda'];
const firstCar = cars[0];
const secondCar = cars[1];

Destructuring assignment provides a cleaner method for this task:

const cars = ['Ford', 'Toyota', 'Honda'];
const [firstCar, secondCar] = cars;

At first glance, seeing array brackets [ ] before the = might seem unusual. A helpful way to think about it is that when [ ] are on the right side of the equals sign, they are used to pack items into an array. When they are on the left side, they do the reverse; they unpack items from an array.

// 'Packing' values into an array:
const array = [1, 2, 3];

// 'Unpacking' values from an array:
const [first, second, third] = array;

While this feature won't fundamentally change how you code, it's a useful technique that can make your code neater.

Skipping Elements

What if you need to get the second element, but not the first? Is this possible with destructuring? Yes, it is:

const cars = ['Ford', 'Toyota', 'Honda'];
const [, secondCar] = cars;

Notice we removed firstCar but left the comma in its place. This comma acts as a placeholder for the element we want to ignore. You can use this technique to create multiple gaps and select only the specific items you need:

const cars = ['Ford', 'Toyota', 'Honda', 'BMW', 'Audi'];

const [, secondCar, , , fifthCar] = cars;

console.log(secondCar); // ‘Toyota’
console.log(fifthCar); // ‘Audi’

While this is an interesting feature of destructuring, it might not be the best approach for complex scenarios. In such cases, using the standard index-based access can be more straightforward and readable:

const secondCar = cars[1];
const fifthCar = cars[4];
00:00

Table of Contents