Skip to content
Advertisement

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?

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement