Sub topic 11
Where Optional Chaining Is Not Allowed
This chapter assumes you already know how ?., ?.[] and ?.() work, and how an optional chain short-circuits when it reaches null or undefined. It covers where the language rejects optional chaining, and the cases where ?. gives you no protection.
The limits come from one rule. An optional chain is an expression that might produce undefined without ever reaching its target. That works when you read a value. It does not work when you write a value, construct an object, or refer to a name that was never declared.
Optional Chains Cannot Be Assigned To
An assignment needs a real location to store a value. If user were null, user?.name = "Ada" would have nowhere to put "Ada". JavaScript rejects this at parse time, so the whole script fails to load. The error does not wait until that line runs.
The same rule applies to every form that writes through a chain:
| Code | Result |
|---|---|
| `user?.name = "Ada"` | SyntaxError |
| `user?.count++` | SyntaxError |
| `user?.count += 1` | SyntaxError |
| `({ a: user?.name } = source)` | SyntaxError (destructuring target) |
| `for (user?.key in obj) {}` | SyntaxError |
| `delete user?.name` | Allowed, returns `true` if `user` is nullish |
delete is the exception. Deleting something that does not exist is already harmless in JavaScript, so the language allows it.
When you need a conditional write, check the object explicitly:
const user = {};
if (user != null) {
user.name = "Ada";
}
console.log(user.name); // "Ada"No Optional Chaining with new or Tagged Templates
new Foo?.() is a SyntaxError. A new expression must produce an object, and a short-circuited chain would produce undefined. Tagged templates such as `obj?.tagtext ` are rejected for a similar reason.
You can confirm all of these parse errors at runtime by compiling the code with new Function. Because the parser throws, you can catch the error:
const snippets = [
"const user = {}; user?.name = 'Ada';",
"const user = {}; user?.count++;",
"function Foo() {} new Foo?.();",
"const obj = {}; obj?.tag`text`;",
];
for (const code of snippets) {
try {
new Function(code);
console.log("OK: ", code);
} catch (err) {
console.log(err.name + ":", code);
}
}
// Every line prints "SyntaxError: ..."The error messages differ between engines, so the code prints only err.name.
?. Does Not Rescue Undeclared Variables
?. checks the value on its left. That value must exist as a variable first. If the name was never declared, the engine throws before ?. can run:
try {
undeclaredVar?.prop;
} catch (err) {
console.log(err.name); // "ReferenceError"
}
console.log(typeof undeclaredVar); // "undefined" (typeof is safe)
console.log(globalThis.undeclaredVar?.prop); // undefinedTo probe for an optional global, such as a browser-only API, access it as a property of globalThis, or use typeof.
?.() Only Guards Against Nullish Values
?.() skips the call only when the callee is null or undefined. If the value exists but is not a function, the call still throws:
const config = { onSave: "yes" };
try {
config.onSave?.();
} catch (err) {
console.log(err.name); // "TypeError": config.onSave is not a function
}If a property might hold a non-function value, check it with typeof config.onSave === "function".
Exercise
For each line, say whether it is valid, a SyntaxError, a ReferenceError, or a TypeError (assume settings = { theme: 5 } is declared and missing is not): (1) settings?.theme = "dark" (2) delete settings?.theme (3) settings.theme?.() (4) missing?.value
Show answer
(1) SyntaxError, because an optional chain cannot be an assignment target. (2) Valid, because delete is allowed on optional chains. (3) TypeError, because 5 is not nullish, so the call goes ahead and fails since 5 is not a function. (4) ReferenceError, because missing was never declared and ?. cannot protect an undeclared name.
Exercise
Rewrite cache?.hits++ so that it increments hits only when cache exists, without causing a SyntaxError.
Show answer
if (cache != null) { cache.hits++; }. The explicit check guards the write, and cache.hits++ is a normal assignment target.