javascriptoptional-chaining

Why does optional-chaining multiple property accesses throw for an empty object, but not for null?


in a node repl or browser console:

> ({})?.a
undefined
> (null)?.a
undefined
> (null)?.a.b
undefined
> ({})?.a.b
Uncaught TypeError: Cannot read properties of undefined (reading 'b')

if (anything)?.a is undefined then why does the undefined that (null)?.a evaluates to NOT throw an error when I read its non-existent properties?


Solution

  • why does the undefined that (null)?.a evaluates to NOT throw an error when I read its non-existent properties?

    It would:

    > (null?.a).b
    Uncaught TypeError: Cannot read properties of undefined (reading 'b')
    > const temp = null?.a;
    > temp.b
    Uncaught TypeError: Cannot read properties of undefined (reading 'b')
    

    The difference from that to null?.a.b is that the optional chaining operator short-circuits the entire property access (and method call) chain, stopping evaluation and just returning undefined.