An Interest In:
Web News this Week
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
- March 26, 2024
June 15, 2021 04:12 am GMT
Original Link: https://dev.to/hidaytrahman/object-destructuring-in-javascript-21h8
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:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To