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
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:
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 whethera
is undefined before trying to access its propertiesIt would:
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 returningundefined
.