I am using optional chaining quite often, but so far never encounter that issue, until today:
if both items can be undefined, rather don't use optional chaining. Only last test (below) can help in practical situations ().

const f = {a:1};
const g = {a:1, b:2};
    console.log(f?.c === g.c);
    console.log(f?.c === g?.c);
    console.log(f.c && f.c === g.c);

When reading "... the expression short circuits and evaluates to undefined instead of throwing an error", I was misleadingly understanding that the 'short-circuit' could help me to skip the test. Any other case where to know that (undefined === undefined) is not undecidable in JavaScript?

2 Replies 2

Optional chaining only applies to the accessor expression where it is in. That is exactly what it says in the MDN article on Optional chaining where you got the quote from. Emphasis mine:

If the object accessed or function called using this operator is undefined or null, the expression short circuits and evaluates to undefined instead of throwing an error.

It applies to the property access. Not any and all expressions. Were it to be the case, then optional chaining would be vastly less useful. A most typical usage would be something like

const myValue = config?.property ?? "default value";

Which is a short and convenient way to have a fallback if there is no configuration.

However, were it true that optional chaining short circuits the entire expression, the semantics would change such that the code would never produce the default value. Only the value of config.property (if it exists) or undefined (if it does not).

The point of the optional chaining is to have a null-safe accessor. Not to take over and nuke the result of any expression it is used in. There is no logic to that.

Any other case where to know that (undefined === undefined) is not undecidable in JavaScript?

No idea, honestly. The optional chaining makes logical and intuitive sense. It follows quite normal ergonomics and affordances to code. It works consistently with other languages and even other language alternatives. I would have never expected it works differently.

@VLAZ you are totally right. My mistake is that I didn't suspect the consequences of (undefined===undefined) is true, hence dangerous. I have to review my old code, where it may have happened silently.

Your Reply

By clicking “Post Your Reply”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.