JavaScript · Destructuring Assignment with Default Values

2018-08-03 ·

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);
console.log(age);
Zaiste
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.

Copyright © 2019 All rights reserved.
Powered by Kulfon.