Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 9, 2022 08:04 pm GMT

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 = {  firstname: "Rahul",  lastname: "thakur",  email: "[email protected]",};let userName = user.name;let userAge = user.age;

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 .


Original Link: https://dev.to/rahulmandyal/javascript-object-destructuring-all-you-need-to-know-about-object-destructuring-5ca3

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To