I ran these experiments in the Chrome console:
a = {}
-> {}
a.n.n.n.n.n.n.n
-> Uncaught TypeError: Cannot read properties of undefined (reading 'n')
a?.n.n.n.n.n.n.n
-> Uncaught TypeError: Cannot read properties of undefined (reading 'n')
a?.n?.n.n.n.n.n.n
-> undefined
Based on my understanding of that operator, I would have expected an error unless all "dots" have a preceding question mark: The subexpression a?.n?.n should result in undefined, and the subsequent .n should crash. However, after doing ?.n two times, something seems to change and reading the property n of undefined seems to be okay, which is obviously nonsense. So something else is probably going on.
One might think that ?. shortcuts the whole remaining expression when evaluated on undefined, but this cannot be the case either, otherwise a single ?. should be sufficient to achieve that.
How exactly does ?. behave, and how does that behaviour explain the results I’m getting?
>Solution :
Quoting from the question:
One might think that ?. shortcuts the whole remaining expression when evaluated on undefined
Yes, that is exactly what is happening. From MDN:
The optional chaining (?.) operator accesses an object’s property or calls a function. If the object accessed or function called using this operator is undefined or null, the expression short circuits and evaluates to undefined instead of throwing an error.
When you access a.b.c or a?.b.c
aevaluates to the empty objecta.bevaluates to undefineda.b.cthrows an error because you are accessingcproperty from undefined.
Note that adding ?. after a is unnecessary here because a is not nullish.
But, in case of a?.b?.c.d or a.b?.c.d
aevaluates to an object anda?.bevaluates to undefined like before.- When evaluating
a?.b?.c: sincea.bis undefined, it doesn’t access thecproperty and short circuits here and returns undefined value for the entire expression