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?
Quoting from the question:
Yes, that is exactly what is happening. From MDN:
When you access
a.b.cora?.b.caevaluates to the empty objecta.bevaluates to undefineda.b.cthrows an error because you are accessingcproperty from undefined.Note that adding
?.afterais unnecessary here becauseais not nullish.But, in case of
a?.b?.c.dora.b?.c.daevaluates to an object anda?.bevaluates to undefined like before.a?.b?.c: sincea.bis undefined, it doesn't access thecproperty and short circuits here and returns undefined value for the entire expression