Array Destructuring in ES6

Facebooktwitterredditpinterestlinkedinmailby feather

Array Destructuring in ES6

The term ‘Destructuring’ is defined as dividing the complicated data structure into easier modules. The Destructuring syntax helps to extract the small segments from an array and the objects. We can also use it for value assignment and variable declaration.

In other words, the process of Destructuring is an effective way for extracting values from data stored in an object or an array. When we are destructuring an array, we have to use the address at the time of the assignment.

Example

Here, we have an example to understand this concept.

Output

After the execution of the code, we will get the following output.

Array Destructuring in ES6

We have another example of Array Destructuring given below-

Example

Output

After the execution of the code, we got the following output:

Array Destructuring in ES6

In the above example, we declared an array named animals containing five values. But we select the three random values that are Cow, Elephant, Dog, addressed at positions 1, 2, 3.

Important Point: If we use any number for array destructuring, then it will return an error because numbers do not have the variable name.

Array Destructuring with Default Values

If the value of any variable is undefined or unassigned in an array, then it will execute with a default value.

Example

Here, we have an example to illustrate the above concept.

Output

After the execution of the code, we got the following output:

Array Destructuring in ES6

Array Destructuring with rest operator

The rest operator(…) in the array destructuring helps to store the enduring elements in a new array.

Here, we have an example to understand this concept.

Example

Output

After the successful execution of the code, we got the following output:

Array Destructuring in ES6

Variable Swapping

We can swap the values of two variables within the single destructuring expression. We can easily swap the values of variables without any temporary variables.

Example

Here, we have an example of variable swapping.

Output

After the execution of the example, we got the following output:

Array Destructuring in ES6

Parsing return array from a function

In the programming, a function is used to return the values of an array. We can easily get an array with the help of a function. The array destructuring helps to define this whole process concisely.

Example

We have an example to understand this concept.

Output

After the execution of the code, we got the following output:

Array Destructuring in ES6
Facebooktwitterredditpinterestlinkedinmailby feather