Object destructuring with JavaScript

Here is something I see very often while reviewing Angular code for the Angular certification program:

While the above code works, it is very lengthy and repetitive. It also increases your code base’s size, negatively impacting performance. Instead, we can use a modern JavaScript syntax introduced with ES6/ES2015 called object destructuring:

The above line of code does the same as the three previous lines. What if we want the local variable to have a different name than the original property? Say we want to name our new variable homeAddress instead of address. We can do it like this:

What if we want those variables to have a default value in case they are not defined in this.user? We can do that too:

Now you know everything you need about object destructuring.

Alain Chautard

Alain is a Google Developer Expert in Web Technologies, Angular, and Google Maps. His daily mission is to help development teams adopt Angular and build at scale with the framework. He has taught Angular on all six continents! A world traveler and photographer, Alain is also an international conference speaker, and a published author of several video courses.