DEV Community

loading...
Cover image for JavaScript · Destructuring Assignment with Default Values

JavaScript · Destructuring Assignment with Default Values

zaiste profile image Zaiste Originally published at zaiste.net ・1 min read

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.

Discussion (1)

pic
Editor guide
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.