optional question mark and object destruction

Viewed 230
const { isSaved } = props?.options;

does this code make sense? what's the purpose of using ? here?

is it better if I do

const { isSaved = null } = props.options;
1 Answers

The first code does not make sense. With optional chaining, when any part of the chain fails, the whole expression will evaluate to undefined. But you can't access properties of undefined, so if the chain fails, the engine will throw:

const props = undefined;
const { isSaved } = props?.options;

But in React, props, if you're referring to what's normally referred to as props, will always be truthy. At worst, it'll be an empty object.

Your second code makes more sense, but it will still throw if options happens to not be a prop:

const props = {};
const { isSaved = null } = props.options;

Alternate with the empty object instead:

const props = {};
const { isSaved = null } = props.options || {};
console.log(isSaved);

Related