Want to get better at Web Development 🚀🚀🚀? Subscribe to my weekly newsletter at https://codesnacks.net/subscribe/
Learn how to set default values when destructuring objects in JavaScript.
Let's briefly see again how destructuring works:
const pastry = {
name: "waffle"
};
const { name } = pastry;
console.log(name); // waffle
Let's see what happens when we try to access a property of the pastry object that doesn't exist:
const pastry = {
name: "waffle"
};
const { sweetness } = pastry;
console.log(sweetness); // undefined
The destructuring mechanism lets us set a default value in the case when the property is undefined.
const { sweetness = 70 } = pastry;
console.log(sweetness); // 70
The default is only set if the property is actually undefined. So it will not set the default for other nullish values like false, null, or 0.
You can even combine defaults and renaming. Let's briefly see how renaming works.
const pastry = {
name: "waffle",
tastiness: 100,
};
// let's get the value of tastiness and store it in deliciousness
const { tastiness: deliciousness } = pastry;
console.log(deliciousness); // 100
// and now let's combine renaming and defaults
// tastiness is set, so no default will be used
const { tastiness: palatability = 75 } = pastry;
console.log(palatability); // 100
// sweetness is undefined; the default will be used
const { sweetnewss: sweet = 50 } = pastry;
console.log(sweet); // 50
Want to get better at Web Development?
🚀🚀🚀subscribe to the Tutorial Tuesday ✉️newsletter
Top comments (2)
😭! I didn't know you can do this with destructuring. what a game changer. Thanks for the post!!
I always get burned by
nullgetting passed for certain values and end up having to check regardless 😢