dtudury
dtudury

Reputation: 639

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?

Upvotes: 2

Views: 187

Answers (2)

Bergi
Bergi

Reputation: 664164

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.

Upvotes: 2

jmcgriz
jmcgriz

Reputation: 3358

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

Upvotes: 4

Related Questions