Search code examples
javascriptnullabledestructuring

How to protect code from destructuring a null value in Javascript?


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?


Solution

  • 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);