ES6 Array destructuring
Destructuring means to break down a complex structure into simpler parts. With the syntax of destructuring, you can extract smaller fragments from objects and arrays. It can be used for assignments and declaration of a variable.
Destructuring is an efficient way to extract multiple values from data that is stored in arrays or objects. When destructuring an array, we use their positions (or index) in an assignment.
Let us try to understand the array destructuring by using some illustrations:
Example
In the above example, the left-hand side of destructuring assignment is for defining what values are required to unpack from sourced variable.
Output
Hello World
Let us take another example of array destructuring.
Example
Output
Violet Indigo Blue
Example
If you want to choose random elements from the given array then in array destructuring you can perform it as follows:
In the above example, we have defined an array named colors which has seven elements. But we have to show three random colors from the given array that are Violet, Blue, and Yellow. These array elements are in positions 0, 2, and 4.
During destructuring, you have to leave the space for unpick elements, as shown in the above example. Otherwise, you will get unintended results.
Output
Violet Blue Yellow
Note: We cannot use numbers for destructuring. Using numbers will throw an error because numbers cannot be the name of the variable.
Array destructuring and Rest operator
By using the rest operator (…) in array destructuring, you can put all the remaining elements of an array in a new array.
Let us try to understand it with an example.
Example
Output
Violet Indigo [ 'Blue', 'Green', 'Yellow', 'Orange', 'Red' ]
Array destructuring and Default values
If you are taking a value from the array and that value is undefined, then you can assign a default value to a variable.
Example
Output
100 70
Swapping Variables
The values of the two variables can be swapped in one destructuring expression. The array destructuring makes it easy to swap the values of variables without using any temporary variable.
Example
Output
200 100
Parsing returned array from functions
A function can return an array of values. It is always possible to return an array from a function, but array destructuring makes it more concise to parse the returned array from functions.
Let us understand it with an example.
Example
In the above example, we have defined the array() function, which returns an array containing three elements. We used array destructuring to destructure the above array elements into specific elements x, y, and z in a single line of code.
Output
100 200 300