JS: proper way of using optional chaining?

Viewed 61

I am just trying to understand at what level of an object to use optional chaining. If I have the given object

foo: {
    other: {
        name: "Bill"
    }
}

rather than do this:

if (foo && foo.other && foo.other.name) { ... }

I want to use optional chaining but I always finding myself just adding ?. at every level.

would the proper way be to add it to every level like this:

if (foo?.other?.name) {

}

or can you leave the last one out since that will result in false if it's not there:

if (foo?.other.name) {

}
1 Answers

You'll need to add the ? at every level where the preceding key can return a null value.

const ohNo = this?.data?.set?.can?.break?.at?.any?.level;

If you were to leave out any ? in there, you'd get null reference exceptions when the preceding depth level is null...

Related