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
null
getting passed for certain values and end up having to check regardless π’