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
?
CodePudding user response:
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
CodePudding user response:
The difference is between trying to access a (potentially) non-existent variable vs a (potentially) non-existent property.
From MDN:
On reference errors:
The
ReferenceError
object represents an error when a variable that doesn't exist (or hasn't yet been initialized) in the current scope is referenced.
This is the case in your first example:
const value = w?.y;
// ^ ReferenceError occurs here
console.log(value);
The
?.
operator is like the.
chaining operator, except that instead of causing an error if a reference is nullish (null
orundefined
), the expression short-circuits with a return value ofundefined
.
This is the case in your second example:
let w;
const value = w?.y;
// ^ Reference exists (but it is undefined)
console.log(value);
CodePudding user response:
I don't know about ecmascript-6. I'm curious what ?. does. Anyways, in js, not defined basically means that its not declared. undefined is just a placeholder.