loading...
Cover image for How to destructure objects in Javascript — beginner’s guide

How to destructure objects in Javascript — beginner’s guide

ari_o profile image Arika O ・2 min read

In the last article I wrote about array destructuring in Javascript. More on this in the link bellow.

Today, I'll continue on the same topic but I'll discuss objects. Just a little reminder, destructuring allows us to extract array items or object properties, multiple at a time.

Let's look at the syntax below. This is how we used to extract properties from obejects before ES6 was introduced. You can quickly see that the larger the object, the more repetitive code we need to write.

Alt Text

Now let's take the same code and destructure it following the ES6 way:

Alt Text

The code is much shorter, easier to read and maintain. An important note is that the variables and the properties need to have identical names, otherwise this won't work and on printing we'll get undefined.

Alt Text

If we must give our variables new names, we can do so by adding a colon after the initial name + the desired name. You can see this in action in the example below.

Alt Text

We can use the rest operator to store in a new object all the properties we didn't want in individual variables. Like so:

Alt Text

Using the same rest operator, we can clone objects. A very useful feature when we want to manipulate an object but we don't want to change any of the original properties. This happens to be my favorite use case for object destructuring, especially when working with React.

Alt Text

Discussion

pic
Editor guide
Collapse
detzam profile image
webstuff

Is
Const {var1, var2, varX} = object
A 2015 feature?

Collapse
ari_o profile image
Arika O Author

Looks like object destructuring to me so I would say yes, it is.