Sub topic 11
Where Optional Chaining Is Not Allowed
This chapter assumes you already know how ?. short-circuits property access, bracket access and calls, and how ?? supplies defaults. Here the focus is on the places where the language rejects ?., plus a few runtime errors that ?. does not prevent. Some of these mistakes stop the whole file from loading, so it helps to recognize them on sight.
Two kinds of failure come up in this chapter:
- Early errors are
SyntaxErrors raised while the engine parses the code. Nothing in the file runs, not even the lines above the mistake. - Runtime errors happen while the code runs. The syntax is valid, but
?.does not guard against the problem.
A Harness for Testing Invalid Syntax
You can't put a SyntaxError in a normal script and keep running, because the parser rejects the whole file. To see each case in one run, compile each snippet separately with new Function. A parse failure throws when the function is created. A runtime failure throws when it is called.
function check(label, src) {
let fn;
try {
fn = new Function(src);
} catch (e) {
console.log(`${label.padEnd(28)} parse error: ${e.name}`);
return;
}
try {
console.log(`${label.padEnd(28)} ok: ${String(fn())}`);
} catch (e) {
console.log(`${label.padEnd(28)} runtime error: ${e.name}`);
}
}
check("assignment", "const o = {}; o?.a = 1;");
check("compound assignment", "const o = {}; o?.a += 1;");
check("increment", "const o = { a: 1 }; o?.a++;");
check("destructuring target", "const o = {}; ({ x: o?.a } = { x: 1 });");
check("array destructuring target", "const o = {}; [o?.a] = [1];");
check("for-of target", "const o = {}; for (o?.a of [1]) {}");
check("new with ?.()", "class Foo {} return new Foo?.();");
check("new with ?. member", "const ns = { Foo: class {} }; return new ns?.Foo();");
check("tagged template", "const o = { t: (s) => s[0] }; return o?.t`hi`;");
check("delete", "const o = null; return delete o?.a;");
check("new result then ?.", "class Foo { b = 'x'; } return new Foo()?.b;");
check("private field", "class A { #x = 1; static read(o) { return o?.#x; } } return A.read(null);");
check("undeclared variable", "return undeclaredVar?.prop;");
check("typeof undeclared chain", "return typeof undeclaredVar?.prop;");
check("globalThis lookup", "return globalThis.undeclaredVar?.prop;");
check("ternary with decimal", "const cond = true; return cond?.5:1;");Running this in Node.js 14 or later, or in a current browser console, prints:
assignment parse error: SyntaxError
compound assignment parse error: SyntaxError
increment parse error: SyntaxError
destructuring target parse error: SyntaxError
array destructuring target parse error: SyntaxError
for-of target parse error: SyntaxError
new with ?.() parse error: SyntaxError
new with ?. member parse error: SyntaxError
tagged template parse error: SyntaxError
delete ok: true
new result then ?. ok: x
private field ok: undefined
undeclared variable runtime error: ReferenceError
typeof undeclared chain runtime error: ReferenceError
globalThis lookup ok: undefined
ternary with decimal ok: 0.5The private field case needs ES2022 support, which means Node.js 14.6 or later. The sections below explain each group.
Optional Chains Cannot Be Written To
An optional chain is a read-only expression. It can never appear on the left side of =, and every other form of writing to it is also rejected.
The rule has a reason. If user?.name = "Ada" were legal, then when user is null the statement would have to do nothing without any signal. A write that can vanish silently is a bug waiting to happen, so the specification makes it an early error.
The same rule covers several forms that people forget are writes:
| Form | Example | Result | Column | Column |
|---|---|---|---|---|
| Plain assignment | `o?.a = 1` | SyntaxError | ||
| Compound assignment | `o?.a += 1`, `o?.a | = 1`, `o?.a ??= 1` | SyntaxError | |
| Increment or decrement | `o?.a++`, `--o?.a` | SyntaxError | ||
| Object destructuring target | `({ x: o?.a } = src)` | SyntaxError | ||
| Array destructuring target | `[o?.a] = src` | SyntaxError | ||
| Loop binding | `for (o?.a of list)`, `for (o?.a in obj)` | SyntaxError | ||
| Deletion | `delete o?.a` | Allowed |
Note that ??= is only rejected when its left side is an optional chain. o.a ??= 1 is fine, and o?.a ?? 1 (a read) is fine.
Rewriting a Conditional Write
When the object might be missing and you want to write only if it exists, say so with an explicit condition:
const user = { stats: null };
// Write only if the object exists
if (user.profile) {
user.profile.name = "Ada";
}
// Increment a counter only if the container exists
if (user.stats) {
user.stats.count = (user.stats.count ?? 0) + 1;
}
console.log(user); // { stats: null }When the right behavior is to create the missing object and then write, combine ??= with a normal member access. The parenthesized assignment returns the object, which is then a valid base for .port:
const config = {};
(config.server ??= {}).port = 8080;
(config.server ??= {}).host = "localhost";
console.log(config); // { server: { port: 8080, host: 'localhost' } }Why delete Is the Exception
delete does not write a new value. It removes a property, and when there is no object there is nothing to remove. So delete o?.a is allowed. If o is nullish, the expression short-circuits and returns true, the same value delete returns for a property that does not exist.
let cache = null;
console.log(delete cache?.entry); // true, nothing happened
cache = { entry: 42 };
console.log(delete cache?.entry); // true, property removed
console.log(cache); // {}Optional Chains and new
You cannot put an optional chain between new and its argument list. Both new Foo?.() and new ns?.Foo() are early errors. Constructing something that might not exist has no sensible result, and allowing it would complicate the grammar for new, which already has subtle rules about where its arguments end.
Optional chaining on the result of new is fine, because new Foo() is a complete expression that produces an object:
class Widget {
constructor() {
this.meta = null;
}
}
console.log(new Widget()?.meta?.id); // undefinedTo construct only when a constructor is present, test it first:
const registry = new Map([["Date", Date]]);
function create(name, ...args) {
const Ctor = registry.get(name);
return typeof Ctor === "function" ? new Ctor(...args) : undefined;
}
console.log(create("Date", 0) instanceof Date); // true
console.log(create("Missing")); // undefinedThe typeof check is stricter than a nullish check. It also rejects values that exist but cannot be constructed, which a ?.-style guard would let through to a TypeError.
Optional Chains and Tagged Templates
A tagged template calls a function with a template literal, as in ` html<p>${x}</p> . Neither o?.tagtext nor ` tag?.text `` is allowed. Both are early errors.
If the tag might be missing, decide what the fallback should be and write it out. Keep the method call on the object so this stays bound:
const formatter = {
prefix: ">> ",
tag(strings, ...values) {
return this.prefix + strings.reduce((out, s, i) => out + s + (values[i] ?? ""), "");
},
};
const name = "Ada";
const text = formatter.tag ? formatter.tag`Hello ${name}` : `Hello ${name}`;
console.log(text); // ">> Hello Ada"super and Other Bases
super is not an ordinary value, so super?.method() is a SyntaxError. The method access itself can be optional: super.method?.() is valid and calls the parent method only if it exists.
class Base {}
class Child extends Base {
init() {
return super.setup?.() ?? "no parent setup";
}
}
console.log(new Child().init()); // "no parent setup"Private fields work as a chain step. o?.#x is valid inside the class body and returns undefined when o is nullish. It still throws a TypeError if o is a non-nullish object that lacks the private field, because ?. only checks for null and undefined.
What ?. Does Not Protect Against at Runtime
Some mistakes parse fine and still throw.
Undeclared Variables
?. checks the value on its left. To get a value, the engine must first resolve the name, and an undeclared name throws a ReferenceError before ?. gets to check anything. Wrapping the chain in typeof does not help either. typeof only shields a bare identifier, and typeof undeclaredVar?.prop has to evaluate the chain first.
For globals that may not exist, such as window in Node.js or a script-injected library, read them as properties of globalThis. Property reads on an existing object return undefined instead of throwing:
const analytics = globalThis.analytics?.track ?? (() => {});
analytics("page_view"); // safe whether or not a global analytics object exists
console.log(typeof globalThis.window); // "undefined" in Node.js, "object" in browsersValues That Exist but Have the Wrong Type
obj.method?.() skips the call only when method is null or undefined. If method is "oops" or 42, the call runs and throws TypeError: obj.method is not a function. In the same way, value?.length returns undefined for a number but does not check that the value is the type you expected. Use typeof or Array.isArray when the type itself is uncertain.
A Parsing Edge Case: ?. Followed by a Digit
The ternary operator also uses ?, and numbers can start with a decimal point. To keep old code working, the language treats ?. followed by a digit as a ternary ? plus a number, not as optional chaining:
const cond = true;
console.log(cond?.5:1); // 0.5, parsed as cond ? .5 : 1No modern code should rely on this. If you are writing a ternary with decimal literals, add spaces and a leading zero (cond ? 0.5 : 1) so that people reading it, and your linter, see what it does.
Summary Table
| Situation | Valid? | Use instead |
|---|---|---|
| `o?.a = v`, `o?.a += v`, `o?.a++` | No (SyntaxError) | `if (o) o.a = v` |
| `o?.a` as a destructuring or loop target | No (SyntaxError) | Destructure into a local, then write conditionally |
| `delete o?.a` | Yes | — |
| `new C?.()`, `new ns?.C()` | No (SyntaxError) | `typeof C === "function" ? new C() : undefined` |
| `new C()?.a` | Yes | — |
| `` o?.tag`x` `` | No (SyntaxError) | Explicit conditional around the tagged template |
| `super?.m()` | No (SyntaxError) | `super.m?.()` |
| `undeclared?.a` | Parses, throws ReferenceError | `globalThis.undeclared?.a` |
| `o.notAFunction?.()` | Parses, throws TypeError | `typeof o.f === "function"` check |
Exercise
A colleague writes settings?.theme ??= "dark"; to set a theme only when settings exists and theme is missing. What happens, and how would you rewrite it?
Show answer
The file fails to parse with a SyntaxError, because an optional chain cannot be the left side of any assignment, including ??=. One correct rewrite is if (settings) settings.theme ??= "dark";. If settings should be created when missing, use (obj.settings ??= {}).theme ??= "dark"; on the object that holds it.
Exercise
Predict the output of each line: (1) let o = null; console.log(delete o?.x); (2) console.log(typeof notDeclared?.x); (3) class P { static make() { return new P()?.missing; } } console.log(P.make());
Show answer
(1) prints true, because delete is allowed on an optional chain and returns true when it short-circuits. (2) throws ReferenceError, because the name notDeclared must be resolved before ?. can test it, and typeof only protects a bare identifier. (3) prints undefined, because ?. after a complete new expression is valid, and the instance has no missing property.
Exercise
Why does new plugins?.Parser() fail while plugins?.Parser followed by a separate new call can work? Write a version that constructs a Parser only when one is registered.
Show answer
An optional chain is not allowed between new and its arguments, so the parser rejects it as an early error. Read the constructor first, then construct conditionally: const Parser = plugins?.Parser; const parser = typeof Parser === "function" ? new Parser() : undefined;