Skip to content
  • Homepage
  • HTML
  • CSS
  • Symfony
  • PHP
  • How to
  • Contact
  • Donate

Teach Developer

Articles, Guides & Tips

How to Object Destructuring in ES6

Home  »  How to • JavaScript • React   »   How to Object Destructuring in ES6
Posted on August 6, 2022August 6, 2022 No Comments on How to Object Destructuring in ES6
594

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 object destructuring is needed. We want to extract data from the object and assign it to new variables. Before ES6, how would this happen?

var person = {name: "John", country: "France", job: "Developer"};

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

console.log(name);//"John"
console.log(country);//"France"
console.log(job);//Developer"

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.

Basic Destructuring

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

var person = {name: "John", country: "France", job: "Developer"};

var {name, country, job} = person;

console.log(name);//"John"
console.log(country);//"France"
console.log(job);//Developer"

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: "John", country: "France", job: "Developer"};

console.log(name);//"John"
console.log(country);//"France"
console.log(job);//Developer"

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

var person = {name: "John", country: "France", job: "Developer"}; 
var name, country, job;

{name, country, job} = person;

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

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 {} left-hand side is considered a block and not an object literal. So let us get this right now.

var person = {name: "John", country: "France", job: "Developer"};
var name, country, job;

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

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

It is also important to note that when using this syntax, they () 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: "John", country: "France", job: "Developer"};

var {name, friends, job} = person;

console.log(name);//"John"
console.log(friends);//undefined

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

Using a new Variable Name

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

var person = {name: "John", country: "France", job: "Developer"};

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

console.log(foo);//"John"
console.log(bar);//"Developer"

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: "John", country: "France", job: "Developer"};

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

console.log(name);//"John"
console.log(friend);//"Annie"

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 assign values to a new variable.

var person = {name: "John", country: "France", job: "Developer"};

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

console.log(foo);//"John"
console.log(bar);//"Annie"

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

The 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: "John", country: "France", job: "Developer"};

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

Combining Arrays with Objects

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

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

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

console.log(foo);//"John"
console.log(bar);//["Annie", "Becky"]

Nesting in Object Destructuring

Objects can also be nested when destructuring.

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

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

console.log(foo);//"John"
console.log(bar);//"France"

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: "John", country: "France", job: "Developer" friends: ["Annie", "Becky"]};

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

console.log(name);//"John"
console.log(friends);//["Annie", "Becky"]
console.log(others);// {country: "France", job: "Developer"}

Here, the remaining properties whose keys were not part of the variable names listed were 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

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 = "John", job: y = "Developer"} = {}) {
    console.log(x);
}

person({name});//"John"

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

Got any questions or addition? Leave a comment.

Thank you for reading. 🙂

How to, JavaScript, React Tags:Javascript

Post navigation

Previous Post: Destructuring Assignment in ES6- Arrays
Next Post: How to check if a customer is logged in to Magento 2 or not?

Related Posts

  • How to Make Toggles With React Hooks
  • How to make a div always float on the screen in the top right corner with CSS?
  • How to fix getFullyear() is not a function with JavaScript?
  • Important most things you should know about JSX
  • Destructuring Assignment in ES6- Arrays
  • How to clear your cache in npm

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Categories

  • Codeigniter (3)
  • CSS (11)
  • eCommerce (1)
  • Framework (1)
  • Git (3)
  • How to (43)
  • HTML (5)
  • JavaScript (15)
  • Jquery (7)
  • Laravel (1)
  • Linux (4)
  • Magento-2 (1)
  • Node js (4)
  • Others (2)
  • PHP (11)
  • React (13)
  • Server (1)
  • SSH (3)
  • Symfony (6)
  • Tips (16)
  • Top Tutorials (10)
  • Ubuntu (3)
  • Vue (1)
  • Wordpress (7)

Latest Posts

  • What is SSH in Linux?
  • How to Delete Files in Ubuntu Command Line
  • How to Deploy a React application on a cPanel
  • How to use events listeners and Event Subscriber in Symfony
  • How to Convert PHP CSV to JSON

WEEKLY TAGS

AJAX (1) Codeigniter (1) Javascript (11) JQuery (1) PHP (16) Programming (1) React (3) Symfony (1)

Random Post

Important most things you should know about JSX
How to Search Recently Modified Files in Linux
How to change background Opacity when the bootstrap modal is open with CSS?
How to use events listeners and Event Subscriber in Symfony
How to use setTimeout and setInterval methods in JavaScript

Quick Navigation

  • About
  • Contact
  • Privacy Policy

© Teach Developer 2021. All rights reserved