Optional Chaining Short Circuits Deep Access

Optional chaining stops evaluating at the first nullish link and returns undefined, with ?.() covering missing methods and ?? supplying defaults.

JavascriptData Integrity

Code

javascriptsnippet
16 lines
// 链路中任何一环是 null/undefined,整个表达式短路成 undefined,不再层层判空
const order = { customer: { address: { city: 'Hangzhou' } } };
console.log('city:', order.customer?.address?.city);
console.log('phone:', order.customer?.phone?.number);

// 可选调用 ?.():方法不存在时不抛错,返回 undefined
const notifier = { send() { return 'sent'; } };
console.log('send:', notifier.send?.());
console.log('cancel:', notifier.cancel?.());

// 与空值合并搭配:短路出的 undefined 落到默认值
console.log('city fallback:', order.customer?.address?.city ?? 'unknown');
console.log('phone fallback:', order.customer?.phone?.number ?? 'no phone');

// 断链的证据:缺失分支返回 undefined,而不是抛 TypeError
console.log('missing branch:', order.customer?.phone?.verified === undefined);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

city: Hangzhou
phone: undefined
send: sent
cancel: undefined
city fallback: Hangzhou
phone fallback: no phone
missing branch: true

How it works

The two opening reads exercise both outcomes of the chain: order.customer?.address?.city finds every link present and evaluates to 'Hangzhou', while order.customer?.phone?.number stops at the missing phone property and evaluates to undefined instead of throwing a TypeError. Optional calls behave the same way — notifier.send?.() invokes the method and returns 'sent', and notifier.cancel?.() short-circuits because no cancel method exists. Pairing the chain with ?? turns each short-circuit undefined into the printed fallback ('unknown' and 'no phone'), and the closing comparison asserts that a broken branch produces undefined — the === undefined check makes the short-circuit observable instead of silent.

What to watch for

  • Nothing third-party is pulled in; the snippet is dependency-free.

This line is where the input actually turns into the result:

const notifier = { send() { return 'sent'; } };

Interactive Tools for This Topic

FAQ

Any setup needed beyond the language runtime?
None — the language runtime is the only requirement.