1

I'm a big fan of destructuring and optional chaining proposal in Javascript.

I couldn't help but feel that when destructuring a null or undefined value it'd be really useful if the result would be undefined as it is in optional chaining instead of throwing an error.

For example:

const person = null
console.log(person?.age) // undefined

However:

const person = null
const { age } = person // runtime error

It doesn't work like this of course but is there some Babel proposal to add this feature? Is there some workaround?

hitchhiker
  • 1,217
  • 4
  • 13
  • 28

2 Answers2

6

It sounds like you might just want to use || {} to destructure an empty object in case person is is null (and happens to also apply if it's otherwise falsey too):

const person = null
const { age } = person || {};
console.log(age);
CertainPerformance
  • 313,535
  • 40
  • 245
  • 254
2

You can use a default value using ||,

const person = null
const { age } = person || {}

console.log(age)

Short circuiting in JavaScript

Code Maniac
  • 35,187
  • 4
  • 31
  • 54