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

Let’s have quick look at the example below:

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

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

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

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.

<Happy Code />

A passionate UI Engineer, Love Travelling and Photography