javascriptoptional-chaining

How does stacking the optional chaining (question-mark-dot) operator in Javascript behave?


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

    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