ES6 - Destructure Array

ES6 JavaScript

In this ES6 tutorial we will learn to destructure array.

Destructuring assignment syntax helps us to unpack values from arrays and properties from objects into distinct variables.

Destructuring array elements into distinct variables

Let's say we have an array of two integers and we want to assign the values to distinct variables. So, we will write the following code.

const numbers = [1, 2];
const [x, y] = numbers;
console.log(x); // 1
console.log(y); // 2

Destructuring array to pick first few elements and discard the rest

Let's say we have an array having five elements and we only want to pick first two elements and save in distinct variables. So, we will write the following code.

const numbers = [1, 2, 3, 4, 5];
const [x, y] = numbers;
console.log(x);  // 1
console.log(y);  // 2

Destructuring array to pick first few elements and save the rest in distinct variable

Let's say we have an array having five elements and we want to save first two elements in a distinct variables x and y and rest of the elements in z. To achieve this we will write the following code.

const numbers = [1, 2, 3, 4, 5];
const [x, y, ...z] = numbers;
console.log(x); // 1
console.log(y); // 2
console.log(y); // [3, 4, 5]

In the above code we are using rest operator.

So, the variable x and y gets assigned the first and second elements respectively of the array while the rest of the elements gets assigned to variable z as we have used the rest ... operator.

Check out ES6 - Rest Parameter.

Destructuring array to pick some elements from selected position

Let's say we have an array of five elements and we want to only pick the first and the third elements of the array. For this we write the following code.

const numbers = [1, 2, 3, 4, 5];
const [x, , y] = numbers;
console.log(x); // 1
console.log(y); // 3

So, the first element of the array gets assigned to the variable x. The second element of the array is skipped. The third element is assigned to the variable y. And the rest of the elements of the array is also skipped.

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT