Language: EN

javascript-destructuracion-arrays

Array Destructuring in JavaScript

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.

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