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