Want to get better at Web Development 🚀🚀🚀? Subscribe to my weekly newsletter at https://codesnacks.net/subscribe/
Destructuring in JS is used to access object properties in an elegant way.
Let's have a look at a JS object:
const pastry = {
name: "waffle",
sweetness: 80,
ingredients: ["flour", "butter", "eggs"],
origin: {
country: "Greece",
name: "obelios",
year: 1200,
}
};
To access its properties we could use the dot notation:
const name = pastry.name;
const sweetness = pastry.sweetness;
const country = pastry.origin.country;
Or with less code, we could use destructuring by specifying the properties, that we want to get.
So instead of
const name = pastry.name;
we can also use
const { name } = pastry;
which looks for the property name inside of the pastry object. It's basically the same as accessing it via pastry.name.
The cool thing is, that you can access multiple properties at once. Let's use the example from above where we accessed name and sweetness.
const { name, sweetness } = pastry;
console.log(name);
console.log(sweetness);
destructuring nested objects
Let's have a look at how to destructure e.g. the country from the origin property.
// const country = pastry.origin.country;
// or
const { origin: { country } } = pastry;
console.log(country); // Greece
You can of course also combine accessing nested and non-nested properties:
const { name, sweetness, origin: { country } } = pastry;
console.log(name);
console.log(sweetness);
console.log(country);
Want to get better at Web Development?
🚀🚀🚀subscribe to the Tutorial Tuesday ✉️newsletter
Top comments (2)
It is funny and interesting at the same time
vishalraj.blog/the-javascript-es6-...