DEV Community

loading...
Cover image for 🧱🧱🧱 object destructuring in JS: setting default values

🧱🧱🧱 object destructuring in JS: setting default values

Benjamin Mock
I'm Ben, a Frontend Developer from Germany working at ebay
Originally published at codesnacks.net ・1 min read

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

Discussion (2)

Collapse
jenbutondevto profile image
Jen

😭! I didn't know you can do this with destructuring. what a game changer. Thanks for the post!!

Collapse
justinsnap profile image
justin-snap

I always get burned by null getting passed for certain values and end up having to check regardless 😒