Array Destructuring in JavaScript

Abdullah Imran
The Startup
Published in
3 min readAug 24, 2020
Photo by Clément H on Unsplash

Destructuring is a convenient way of extracting multiple values from data stored in objects and Arrays. ES6 introduced some significant improvements to the language, including the de-structuring of Objects and Arrays. Honestly speaking, these are my favorite edition in the JavaScript standard syntax.

Array destructuring

Let us take a look if we want to extract data from an array in es5.

Here, we are doing something quite boring stuff and repeated the same thing again and again. But ES6 destructuring assignment makes it easier.

We can also do this with the same result,

we can also declare variables before Assignment,

Assign variables a default value:

Here, you can see that we didn’t assign value for num3 and the console gives no error or undefine message because it takes its default value, and print it.

Swapping Values:

Did you know that two variable values can be swapped in one destructuring assignment? Let’s take an example,

Skipping Items in an Array:

If you want to Skipping Items in an Array, you can also do this by array destructuring. Simply use a comma operator to skip an item on an array.

Rest(…) operator:

Here, num1 is assigned for 1 and the rest of the items on this array are assigned on the particular variable num2.

Destructuring with Functions:

You can extract data from an array returned from a function. Have a look the example below,

I hope this lesson provides a clear understands of how Destructuring works in JavaScript. Hopefully, you learned something today. Happy Coding.

--

--