DEV Community

Cover image for Object destructuring in JavaScript
Hidayt Rahman
Hidayt Rahman

Posted on

Object destructuring in JavaScript

Object destructuring in JavaScript

Object destructuring is a useful JavaScript feature to extract properties from objects and bind them to variables. What’s better, object destructuring can extract multiple properties in one statement, can access properties from nested objects, and can set a default value if the property doesn’t exist.

Normally, we access objects with the key. Nothing new :)

object.key
Enter fullscreen mode Exit fullscreen mode

Let’s have quick look at the example below:

// object (Literal)
var user = {
    name: "Hidayt",
    city: "Delhi",
    type: "Admin"
}
console.log(user.name); // Hidayt
Enter fullscreen mode Exit fullscreen mode

We have a user object which contains user info (name, city, type). We will be using this example for object destructuring.

Object destructuring

Let’s use object destructuring and Destructuring the object into our variables.

// object destructuring
var {name, city, type} = user;
// access as a normal variable
console.log(name); // Hidayt
console.log(city); // Delhi
console.log(type); // Admin
Enter fullscreen mode Exit fullscreen mode

You can access name directly instead of user.name

Now it can be accessible as a normal variable.

Destructuring makes code tidy and easy to access.

Top comments (8)

Collapse
 
yuvgeek profile image
Yuvaraj

Here's my article on Object Destructuring in depth : dev.to/yuvgeek/use-object-destruct...

Collapse
 
hidaytrahman profile image
Hidayt Rahman

Thank you for sharing :)

Collapse
 
enriquesource profile image
EnriqueSource

Thanks.

Collapse
 
hidaytrahman profile image
Hidayt Rahman

I'am glad you liked it :)

Collapse
 
rogerioviana profile image
Rogerio Viana

Nice post

Collapse
 
hidaytrahman profile image
Hidayt Rahman

Thank you :)

Collapse
 
vishalraj82 profile image
Vishal Raj

Here is my detailed article on ES6 destructuring. Might throw more light on the topic.

Collapse
 
hidaytrahman profile image
Hidayt Rahman

Thank you for sharing. Hope people will jump for the depth knowledge