DEV Community

Cover image for JavaScript · Destructuring Assignment with Default Values
Zaiste
Zaiste

Posted on • Originally published at zaiste.net

14 8

JavaScript · Destructuring Assignment with Default Values

The destructuring assignment is a new syntax to get a part of an array or of an object and assign it to a variable in a more convenient way. It is also possible to set default values when using destructuring assignment.

const user = {
  name: 'Zaiste',
}
const { name, age } = user;

console.log(age); // undefined

const creates variables, so in the previous example age is undefined.

const user = {
  name: 'Zaiste',
}
const { name = 'Basia', age = 21 } = user;

console.log(name); // Zaiste
console.log(age); // 21

Default values in destructuring assignement only work if the variables either don't exist or their value is set to undefined. Any other value, including null, false and 0, bypasses the default values in the destructuring statement.

const dummy = {
  name: undefined
}

const { name = 'Basia' } = dummy;
console.log(name) // Basia

while for null:

const dummy = {
  name: null
}

const { name = 'Basia' } = dummy;
console.log(name) // null

You can combine default values with renaming in the destructuring assignment.

const user = {
  name: 'Zaiste',
}
const { name: author = 'Basia', age = 21 } = user;

console.log(author); // Zaiste

This creates author variable, while name is just a label to specify the field to destruct against - it doesn't exist as a separate variable.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (1)

Collapse
 
ggenya132 profile image
Eugene Vedensky

I don't know why but I totally didn't know you could set default destructured arguments! Now it's even more versatile for me.

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay