DEV Community

Sarah Chima
Sarah Chima

Posted on

Object Destructuring in ES6

This is a follow up article to my previous article on Array Destructuring. Except you have an idea of destructuring, you should read it.

First, let's see why there is a need for object destructuring. We want to extract data from an object and assign to new variables. Prior to ES6, how will this be done?

    var person = {name: "Sarah", country: "Nigeria", job: "Developer"};

    var name = person.name;
    var country = person.country;
    var job = person.job;

    console.log(name);//"Sarah"
    console.log(country);//"Nigeria"
    console.log(job);//Developer"
Enter fullscreen mode Exit fullscreen mode

See how tedious it is to extract such data. We have to repeatedly do the same thing. ES6 comes with destructuring to save the day. Let's jump right into it.

Let us repeat the above example with ES6. Instead of assigning it one by one, we can use an object on the left to extract the data.


    var person = {name: "Sarah", country: "Nigeria", job: "Developer"};

    var {name, country, job} = person;

    console.log(name);//"Sarah"
    console.log(country);//"Nigeria"
    console.log(job);//Developer"
Enter fullscreen mode Exit fullscreen mode

You'll get the same results. It is also valid to assign variables to an object that is not declared.

    var {name, country, job} = {name: "Sarah", country: "Nigeria", job: "Developer"};

    console.log(name);//"Sarah"
    console.log(country);//"Nigeria"
    console.log(job);//Developer"
Enter fullscreen mode Exit fullscreen mode

Variables declared before being assigned
Variables in objects can be declared before being assigned with destructuring. Let's try that.

    var person = {name: "Sarah", country: "Nigeria", job: "Developer"}; 
    var name, country, job;

    {name, country, job} = person;

    console.log(name);// Error : "Unexpected token ="

Enter fullscreen mode Exit fullscreen mode

Wait!! What just happened? Ooh, we forgot to add () before the curly brackets.
The ( ) around the assignment statement is required syntax when using object literal destructuring assignment without a declaration. This is because the {} on the left hand side is considered as a block and not an object literal. So let us get this right now.

    var person = {name: "Sarah", country: "Nigeria", job: "Developer"};
    var name, country, job;

    ({name, country, job} = person);

    console.log(name);//"Sarah"
    console.log(job);//"Developer"

Enter fullscreen mode Exit fullscreen mode

It is also important to note that when using this syntax, the () should be preceded by a semi-colon. Else, it might be used to execute a function from the previous line.

Note that the variables in the object on the left hand side should have the same name as a property key in the object person. If the names are different, we'll get undefined. Look at this.

    var person = {name: "Sarah", country: "Nigeria", job: "Developer"};

    var {name, friends, job} = person;

    console.log(name);//"Sarah"
    console.log(friends);//undefined
Enter fullscreen mode Exit fullscreen mode

If we want to use a new variable name... well, we can.

Using a new Variable Name

If we want to assign values of a object to a new variable instead of using the name of the property, we'll do this.

    var person = {name: "Sarah", country: "Nigeria", job: "Developer"};

    var {name: foo, job: bar} = person;

    console.log(foo);//"Sarah"
    console.log(bar);//"Developer"
Enter fullscreen mode Exit fullscreen mode

So the values extracted are passed to the new variables foo and bar.
Using Default Values

Default values can also be used in object destructuring, just in case a variable is undefined in an object it wants to extract data from.

    var person = {name: "Sarah", country: "Nigeria", job: "Developer"};

    var {name = "myName", friend = "Annie"} = person;

    console.log(name);//"Sarah"
    console.log(friend);//"Annie"
Enter fullscreen mode Exit fullscreen mode

So if the value is not undefined, the variable stores the value extracted from the object as in the case of name. Else, it used the default value as it did for friend.

We can also set default values when we assigning values to a new variable.

    var person = {name: "Sarah", country: "Nigeria", job: "Developer"};

    var {name:foo = "myName", friend: bar = "Annie"} = person;

    console.log(foo);//"Sarah"
    console.log(bar);//"Annie"
Enter fullscreen mode Exit fullscreen mode

So name was extracted from person and assigned to a different variable. friend on the other hand was undefined in person, so the new variable bar was assigned the default value.

Computed Property Name

Computed property name is another object literal feature that also works for destructuring. You can specify the name of a property via an expression, if you put it in square brackets.

    var prop = "name";

    var {[prop] : foo} = {name: "Sarah", country: "Nigeria", job: "Developer"};

    console.log(foo);//"Sarah"

Enter fullscreen mode Exit fullscreen mode

Combining Arrays with Objects

Arrays can also be used with objects in object destructuring. An example is given below.

    var person = {name: "Sarah", country: "Nigeria", friends: ["Annie", "Becky"]};

    var {name:foo, friends: bar} = person;

    console.log(foo);//"Sarah"
    console.log(bar);//["Annie", "Becky"]
Enter fullscreen mode Exit fullscreen mode

Nesting in Object Destructuring

Objects can also be nested when destructuring.

    var person = {
        name: "Sarah",
        place: {
            country: "Nigeria", 
            city: "Lagos" }, 
        friends : ["Annie", "Becky"]
        };

    var {name:foo,
         place: {
             country : bar,
             city : x}
          } = person;

    console.log(foo);//"Sarah"
    console.log(bar);//"Nigeria"
Enter fullscreen mode Exit fullscreen mode

Rest in Object Destructuring

The rest syntax can also be used to pick up property keys that are not already picked up by the destructuring pattern. Those keys and their values are copied onto a new object. Look at the example below.

    var person = {name: "Sarah", country: "Nigeria", job: "Developer" friends: ["Annie", "Becky"]};

    var {name, friends, ...others} = person;

    console.log(name);//"Sarah"
    console.log(friends);//["Annie", "Becky"]
    console.log(others);// {country: "Nigeria", job: "Developer"}
Enter fullscreen mode Exit fullscreen mode

Here, the remaining properties whose keys where not part of the variable names listed where assigned to the variable others. The rest syntax here is ...others. others can be renamed to whatever variable you want.

One last thing, let's see how Object Destructing can be used in functions.

Object Destructuring and Functions

Object Destructuring can be used to assign parameters to functions. We can use an example here.

    function person({name: x, job: y} = {}) {
        console.log(x);
    }

    person({name: "Michelle"});//"Michelle"
    person();//undefined
    person(friend);//Error : friend is not defined

Enter fullscreen mode Exit fullscreen mode

Notice the {} on the right hand side of the parameters object. It makes it possible for us to call a function without passing arguments. That is why we got undefined. If we remove it, we'll get an error message.
We can also assign default values to the parameters.

    function person({name: x = "Sarah", job: y = "Developer"} = {}) {
        console.log(x);
    }

    person({name});//"Sarah"
Enter fullscreen mode Exit fullscreen mode

We can do a whole lot of things with Object Destructuring as we have seen in the examples above.

Got any question or addition? Leave a comment.

Thank you for reading. :)

Top comments (18)

Collapse
 
sammyisa profile image
Sammy Israwi

Great article! Picked up some tricks that I wish I knew before...

I always found confusing or misleading the syntax for assigning new variable names in object destructuring. Using : inside an object takes my mind to property assignment from right to left, not new variable assignment from left to right. Also, it is too similar to Typescript's type declaration:

const num: int = 5;

And fairly different (and less verbose than) using new variable names in import object destructuring:

import { Component as Comp} from "React";

Collapse
 
sarah_chima profile image
Sarah Chima

I'm glad you picked up some tricks Sammy. Thank you for reading.

Collapse
 
tobias_grasse profile image
Tobias Grasse

Thanks for this post! I learned some new tricks; your explanations of the pitfalls with object literal destructuring assignment with previous variable declaration were especially insightful :-)

Collapse
 
sarah_chima profile image
Sarah Chima

I'm glad you learnt some new tricks. Thanks for reading.

Collapse
 
sudheer160540 profile image
sudheer160540

Nice article sarah chima. I am learning a lot of things in this article.

Thanks for spending time for writing this article

Collapse
 
sarah_chima profile image
Sarah Chima

I'm glad you like it. 😊

Collapse
 
techtheriac profile image
Franklin Jezreel

This was quite useful. Thank you for watering down the vagueness of the concept.

Collapse
 
kmylo profile image
kmylo • Edited

Rest in Object Destructuring: [ERROR]

var person = {name: "Sarah", country: "Nigeria", job: "Developer" friends: ["Annie", "Becky"]};
Something missing comma between, "Developer" and friends.
Nice article, thx!

Collapse
 
iamtheiam profile image
IAMtheIAM

Thanks for the detailed and accurate explanation of object destructuring!

Collapse
 
ankurrai2602 profile image
Ankur

Thanks for writing a great article which covers a lot of details.

Collapse
 
a1ubkh4n profile image
Md.Aiub Khan

Thank you..Sarah

Collapse
 
rekh profile image
Rekh

Huh, got stuck on Javascript courses about Destructuring, but your post is really clear and will surely help me to defeat the evil forces of those exercices.

Thanks !

Collapse
 
sarah_chima profile image
Sarah Chima

I'm glad you found my post helpful

Collapse
 
spyrosko profile image
spyrosko

This was the most excellent article on object destructuring I've ever read. So thorough and easy to understand.

Collapse
 
sarah_chima profile image
Sarah Chima

Thanks a lot for reading.