2

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

6

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

2
  • 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
    – Caius Jard
    Commented Oct 6, 2020 at 18:04
  • @CaiusJard yea it's unexpected, but it would be even stranger if the feature change did not account for this situation.
    – Pointy
    Commented Oct 6, 2020 at 18:09

Not the answer you're looking for? Browse other questions tagged or ask your own question.