skip to Main Content

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?

2

Answers


  1. It’s working that way to allow you to check if an object exists, and then access multi-level properties if it does without needing a huge tree of checks against every level of the object. The case with (null)? is repeatable in two more ways that illustrate the principle:

    (undefined)?.a.b.c.d 
    ({})?.a?.b.c.d
    

    Both of those will also return undefined without throwing an error. As long as you’ve triggered a fail state with ? already, it will let you reference subproperties safely to as many layers as you like

    ({})?.a.b throws an error because {} is defined and passes the check, but then you’re not checking whether a is undefined before trying to access its properties

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search