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,099
  • 5
  • 19
  • 44

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
  • 356,069
  • 52
  • 309
  • 320
2

You can use a default value using ||,

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

console.log(age)

Short circuiting in JavaScript

Code Maniac
  • 37,143
  • 5
  • 39
  • 60