Oliver Jumpertz

Destructure From An Undefined Object

Category: JavaScript

Share this snippet to:

const { one, two } = obj?.nested ?? {};

Usage

Sometimes, you don’t know whether an object at hand is undefined. If so, destructuring from such an object throws an error you somehow have to deal with. If you don’t want to clutter your code with try-catch statements, you can use optional chaining and the nullish coalescing operator to get a safe fallback.

Here is how you would use it with a function call:

const { propA, propB } = callSomeFunction()?.nested ?? {};

Explanation

The optional chaining operator ensures that up to the deepest call you make, everything is safe from TypeErrors, so no accidental calls on undefined properties. The nullish coalescing operator at the end ensures that you get a safe fallback if the whole chain returns undefined. In this case, the default is returned, and destructuring from an empty objects throws no errors.

You can also decide to use a real fallback option with properties, instead of an empty one, but that depends on your specific use case.


Share this snippet to: