
JavaScript Array Destructuring
The ES6 destructuring assignment allows you to destructure an array into individual variables. ES6 provides a new feature called destructuring assignment that allows you to destructure properties of an object or elements of an array into individual variables.
Let’s start with the array destructuring.
Assuming that you have a function that returns an array of numbers as follows:
function getScore(){
return [70, 80, 90]
}
The following invokes the getScore()
function and assigns the returned value to a variable:
let scores = getScore();
To get the individual score, you need to do like this:
let x = scores[0],
y = scores[1],
z = scores[2];
Before ES6, there was no direct way to assign the elements of the returned array to multiple variables such as x
, y,
and z
.
Fortunately, starting from ES6, you can use the destructing assignment as follows:
let [x, y, z] = getScores();
console.log(x); //70
console.log(y); //80
console.log(z); //90
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 getScores()
function returns an array of two elements, the third variable will be undefined, like this:
function getScores(){
return [70, 80];
}
let [x, y, z] = getScores();
console.log(x); //70
console.log(y); //80
console.log(z); //undefined
In case the getScores() function returns an array that has more than three elements, the remaining elements are discarded. For example:
function getScores(){
return [70, 80, 90,100];
}
let [x, y, z] = getScores();
console.log(x); //70
console.log(y); //80
console.log(z); //90