DEV Community

Cover image for 🧱🧱🧱 object destructuring in JS: setting default values
Benjamin Mock
Benjamin Mock

Posted on β€’ Originally published at codesnacks.net

15 2

🧱🧱🧱 object destructuring in JS: setting default values

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (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 😒

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free β†’