Destructuring object in JavaScript

While developing web application we often come across the need to access the object properties. ES6 has introduced a very useful feature for this purpose, where we can extract the properties from the objects and assign them to variables, so that there is no need of using the dot notation. This feature is termed as object destructuring.

Syntax

let {var1, var2} = {var1:val1, var2:val2}

Order of receiving variable doesn't matter. The only thing to remember here is the receiving variable's name should be same as that of the target property's name.

Why is object destructuring useful

Consider an object

var user = {
  firstName:'John',
  lastName:'Doe',
  email:'john@mail.in'
};

In the pre ES6 scenario, in order to access individual properties we need to use the dot notation and code would look like this:

var firstName = user.firstName;
var lastName = user.lastName;
var email = user.email;

Clearly if the number of properties is more the code will become clumsy. Instead, we can use object destructuring and same results can be achieved in a single line.

var { firstName, lastName, email } = user;

Apart from accessing the properties there are additional things we can do with object destructuring. We will discuss them below.

Alias names

I mentioned above that receiving variable's name should be same as that of the property name. But if the need arises to use a different variable name we can make use of aliasing feature. Let me show aliasing with a snippet:

var { firstName: name } = user;

Here I've used name as the alias name for the property firstName and it is being assigned the value of user.firstName.

There is one more thing to note here, we can unpack as many properties as required and it is not at all important to destructure all the properties at once.

Default value

There may be cases where we are trying to destructure an object and extract a property which may not be present in that object. If the property is not present in the object(also, not present in the prototype chain) then the variable is assigned undefined. This may cause errors in the places where we are accessing that variable. In order to avoid such scenario default values can be assigned to such variable, which means if that property does not exist in the object it can be assigned that default value. For instance,

var { department='IT' } = user

Here the object user is not having department property in it and therefore default value IT will be assign to department.

So object destructuring is an amazing feature which enables us to unpack properties from object into distinct variable in a concise manner.