Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript `?.` operator: why is `not defined` not treated as `undefined`?

Assuming w has not been previously defined, the following JS code gives ReferenceError: w is not defined:

w?.y;

whereas this code simply returns undefined:

let w; w?.y;

Why does the ?. operator not treat not defined as undefined?

like image 452
Luke Hutchison Avatar asked Feb 12 '26 11:02

Luke Hutchison


1 Answers

This is mentioned in the documentation

Optional chaining cannot be used on a non-declared root object, but can be used with an undefined root object.

which means you have to declare the root object, in this case, it's w

like image 151
hgb123 Avatar answered Feb 15 '26 02:02

hgb123



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!