DEV Community

Cover image for How to destructure arrays in Javascript — beginner’s guide
Arika O
Arika O

Posted on • Edited on

How to destructure arrays in Javascript — beginner’s guide

Tired of the traditional property access? ES6 destructuring to the rescue.

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. (MDN)

Although similar to spreading (remember the operator?), it differs from the it in one very important aspect. While spreading an array we must extract all elements, when using destructuring we can extract only a few pieces on information, if that’s what we want (we can of course extract all of them too). It works with arrays and objects but today I am going to write about arrays.

Consider the following code which illustrates the syntax prior to ES6:

Alt Text

Nothing wrong with it and it gets the job done, right? Right. But when using nested arrays, the code can become cumbersome while trying to access certain elements.

Now let’s look at this code:

Alt Text

If we try to print the new variables to the console, we get the exact same result as in the previous example. The difference is that the syntax is clearer, cleaner and shorter.

We just used destructuring to store all the values of an array into individual variables. What if we want to store only a few of them? We can do that too, using the rest () operator. Yes, it looks exactly like the spread operator but it’s used differently. For now, all we need to know is that it must be used with the last item of the array-like-syntax object and it holds all the values that we don’t want to extract individually. We can give the rest variable whatever name we want (yes, even tRex).

Alt Text

We can skip values in an array by simply not writing them and what we get where those values should be in the new array is “undefined”. Like so:

Alt Text

Note that we renamed the "rest" variable to “dinosaur”.

In the next article I’m going to discuss object destructuring in Javascript.

Top comments (2)

Collapse
 
andybroger profile image
Andy Broger

Nice post silvia, thanks for that!

A offtopic question, but i like your keyboard, what brand is it?

Collapse
 
arikaturika profile image
Arika O

Thx. It's actually a stock photo but if I would need to guess, I think the keyboard is something like these:

amazon.com/Taide-Profile-Keycaps-M...