DEV Community

RahulMandyal
RahulMandyal

Posted on • Updated on

All you need to know about object destructuring

As we all know javascript es6 version had came with a lot of feature and it made javascript slightly better .Object destructring also came with the es6 version it somehow also made our job easier .

Before es6 version when we want to assign object properties into a variable we typically do it like this:


let user = {
  name : "Rahul thakur",
  age : 19
};
let userName = user.name;
let userAge = user.age;

Enter fullscreen mode Exit fullscreen mode

But now object destructuring provides us better syntax that can help us to reduce our code and also provide an alternative way to assign properties of an object to a variable:

let {name : username , age : userage} =user;

the syntax is :
{let property1 :variablename , property2 : variablename}= object ;

Make your code more shorter:

If your variable have the same name as the properties of the object then we can make our code more shorter

let {name , age } = user ;``
this is equivalent to the previous one.now instead of writing two two lines of code we can do it within one line of code .

undefined values :

Suppose you are trying to assign a property that does not exits in the object then then variable is set to undefined for example :
Image description
Here in this example phone ,lastname,email is not present inside the user object so those variable which are not present inside the obejct are initialized with the undefiend value.

Setting default values

we can assign a default value to the variable if the property does not exits inside the the object then instead of undefined the variable is initialized with the default value for example :
Image description

Summary

Object destructuring just making our job easier .It provides us better syntax to store object properties value inside variables with in one line of code .

Top comments (0)