The destructuring of arrays is a way to unpack values from arrays and assign them to variables directly.
For example, instead of extracting values from an array using indices, we can do it directly with destructuring.
We will see object destructuring
Basic Syntax
Array destructuring uses brackets ([]
) to assign values to individual variables. The order of the variables matches the order of values in the array. Let’s look at an example:
const numbers = [10, 20, 30];
const [a, b, c] = numbers;
console.log(a); // 10
console.log(b); // 20
console.log(c); // 30
Let’s see it with an example,
const colors = ["red", "green", "blue"];
// Without destructuring
const color1 = colors[0];
const color2 = colors[1];
// With destructuring
const [red, green, blue] = colors;
console.log(red); // "red"
console.log(green); // "green"
console.log(blue); // "blue"
Skipping Elements
You can ignore certain values using commas.
const numbers = [10, 20, 30];
const [, second] = numbers; // Ignores the first value
console.log(second); // 20
In this example, the comma ,
indicates that we are ignoring the first value of the array.
Default Values
If the array does not have enough values, you can assign default values.
const numbers = [10];
const [a, b = 20] = numbers;
console.log(a); // 10
console.log(b); // 20
Usage with Rest Parameters
You can capture the rest of the values in an array using ...
. Remember that the ...
operator must be at the end to capture the rest of the values.
const numbers = [1, 2, 3, 4, 5];
const [first, second, ...rest] = numbers;
console.log(first); // 1
console.log(second); // 2
console.log(rest); // [3, 4, 5]
Practical Examples
Swapping Values with Destructuring
One of the most common applications of destructuring is to swap the value of two variables without using a temporary variable.
let a = 1;
let b = 2;
// Swap values
[a, b] = [b, a];
console.log(a); // 2
console.log(b); // 1
Destructuring with Multidimensional Arrays
When you have an array that contains other arrays (multidimensional arrays), you can destructure it in a nested way.
const matrix = [
[1, 2],
[3, 4],
[5, 6]
];
// Nested destructuring
const [[a, b], [c, d], [e, f]] = matrix;
console.log(a, b); // 1 2
console.log(c, d); // 3 4
console.log(e, f); // 5 6
Destructuring in Loops
You can use destructuring directly within a for
loop to efficiently extract values from an array.
const fruits = [
["apple", 1],
["banana", 2],
["cherry", 3]
];
for (const [fruit, quantity] of fruits) {
console.log(`${fruit}: ${quantity}`);
}
// Output:
// apple: 1
// banana: 2
// cherry: 3
Destructuring with Skipping Multiple Elements
You can skip multiple elements from the array using commas and assign only the elements you are interested in.
const numbers = [10, 20, 30, 40, 50];
// Only assign the first, second, and last element
const [first, second, , , fifth] = numbers;
console.log(first); // 10
console.log(second); // 20
console.log(fifth); // 50