Today, We will learn how to use the ES6 destructuring assignment that allows us to destructure an array into individual variables.
ES6 provides a new feature called destructing assignment that allows you to destructure properties of an object or elements of an array into individual variables.
Let's take an example of a function that returns an array of subject list as follows:
The following invokes the getSubjectList() function and assigns the returned value to a variable:
- Prior to ES6, there was no direct way to assign the elements of the returned array to multiple variables such as x, y and z.
- To get the individual subject to a variable, We need to do like this:
Fortunately, From ES6, We can use the destructing assignment as follows:
The variables x, y and z will take the values of the first, second, and third elements of the returned array.
Note that the square brackets  look like the array syntax but they are not.
If the getSubjectList() function returns an array of two elements, the third variable will be undefined, like this:
In case the getSubjectList() function returns an array that has more than three elements, the remaining elements are discarded.
Array "Destructuring Assignment" with "Rest" Parameter
- It’s possible to take all remaining elements of an array and put them in a new array by using the rest syntax (...):
- The variables x and y receive values of the first two elements of the returned array.
- The args variable receives all the remaining arguments, which are the last two elements of the returned array.
Setting default values
How it works:
- First, declare the getValues() function that returns an array of two numbers.
- Then, assign the dataValue variable to the returned array of the getValues() function.
- Finally, check if the third element exists in the array. If not, assign the value 0 to the thirdItem variable.
It’ll be simpler with the destructuring assignment with a default value:
If the getData() function doesn’t return an array and you expect an array, the destructing assignment will result in an error.
Uncaught TypeError: getData is not a function or its return value is not iterable
A typical way to solve this is to fallback the returned value of the getData() function to an empty array like this:
- We can set user-defined default values if array has returned null or variable has a undefined.