3

Sometimes I have:

let a = { b: { c1: { z: false } } }

Other times I have:

let a = { b: { c2: { z: false } } }

I have let n = 'c1' or let n = 'c2'

I can do this to propagate the undefined:

a?.b[n]?.z

But other than if(a.b) ..., can I do anything shorthand if b is undefined?

There isn't a ?[ it seems, and I don't think I can do a['b'][n]?.z either, because if there is no b then attempting to index n on it will give cannot read property VALUE_OF_N of undefined ?

1 Answer 1

8

Yes:

a?.b?.[n]?.z

The ?. operator can be used before a [ ] expression. It looks odd, but ?. is itself a complete token so it syntactically makes sense. In other words, ?. normally isn't just a question mark before the usual . operator; it's an entire operator unto itself.

let a;
let n;

a = { b: { c1: { z: false } } }
n = 'c1';

console.log(a?.b[n]?.z);

a = { b: { c2: { z: false } } }
n = 'c2';

console.log(a?.b?.[n]?.z);

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks.. I hadn't realized this because a.[n] is invalid, so I was thinking "[ may not have anything before it" and I'd missed the "syntax" box on developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… - i see it works for funcs too
@CaiusJard yea it's unexpected, but it would be even stranger if the feature change did not account for this situation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.