E2EHIRING Logo
search

Search blogs by title

Jobs
Jobs
internships
Internships
Company
Partners
mentorship
Mentorship
more
Moredropdown
Login
HomeSepratorIconBlogsSepratorIconJavaScript Array DestructuringSepratorIcon

JavaScript Array Destructuring

Han SoloPriyanka Siddalingreddy
calendar30 Jun 2022
poster

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.

Introduction to JavaScript 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

Recent Posts

Innovation is the Need of the Hour: Else you are Outdated

Innovation is the Need of the Hour: Else you are Outdated

Router In React

Router In React

Higher Order Component in React

Higher Order Component in React

Styled Component in React

Styled Component in React

Spring - Bean Life Cycle

Spring - Bean Life Cycle

copycopycopycopy

Han Solo

Recent Posts

Innovation is the Need of the Hour: Else you are Outdated

Innovation is the Need of the Hour: Else you are Outdated

Router In React

Router In React

Higher Order Component in React

Higher Order Component in React

Styled Component in React

Styled Component in React

Spring - Bean Life Cycle

Spring - Bean Life Cycle

e2e logo