0

In Javascript it is possible to deconstruct objects and supply default values to declare variables. Below the name property of school object inside user object would be assigned to the name variable. However this also happens for undefined variables.

const user = {
 id: 339,
 name: 'Fred',
 age: 42,
 education: {
  school: {
   name: undefined
  }
 }
}
const {education: {school: {name}} = {school: {name: 'Dunno'}}} = user;
console.log(name); //prints: undefined

Above example is from Destructuring Nested Objects

Is there a way to guard against that inside the deconstruction so that name would print the default 'Dunno'?

Björn
  • 12,587
  • 12
  • 51
  • 70
  • 2
    `const {education: {school: {name = 'Dunno'}}} = user;` – Keith Mar 25 '19 at 14:30
  • ah yeah, `const {education: {school: {name = 'Dunno'} = {}} = {}} = user` works, but it is a different syntax. How to make it work with the syntax from question? – Björn Mar 25 '19 at 14:34
  • Either make sure you have education in your second one, or don't destruct education in the first place. Why are you wanting to destructor twice anyway? – Keith Mar 25 '19 at 14:37
  • Ah, I just realised my question does not make much sense because it is deconstructing/defaulting the whole education object first. thx @Keith for the answer. – Björn Mar 25 '19 at 14:43

0 Answers0