Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
June 15, 2021 04:12 am GMT

Object destructuring in JavaScript

Object destructuring in JavaScript

Object destructuring is a useful JavaScript feature to extract properties from objects and bind them to variables. Whats 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 doesnt exist.

Normally, we access objects with the key. Nothing new :)

object.key

Lets 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

Lets use object destructuring and Destructuring the object into our variables.

// object destructuringvar {name, city, type} = user;// access as a normal variableconsole.log(name); // Hidaytconsole.log(city); // Delhiconsole.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.


Original Link: https://dev.to/hidaytrahman/object-destructuring-in-javascript-21h8

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