Optional Chaining With Nullish Defaults
Traverse possibly-missing data with optional chaining and fall back with nullish coalescing so falsy values are not clobbered.
Code
const payload = {
user: { profile: { nickname: 'ada' }, prefs: { pageSize: 0 } },
};
// 可选链:中途缺失返回 undefined 而不是抛错
console.log(payload.user?.profile?.nickname);
console.log(payload.user?.contact?.email);
console.log(payload.missing?.deep?.value);
// ?? 只在 null/undefined 时兜底:0 与 '' 得以保留
const pageSize = payload.user?.prefs?.pageSize ?? 25;
const theme = payload.user?.prefs?.theme ?? 'dark';
console.log('pageSize:', pageSize, 'theme:', theme);
// || 的陷阱:0 会被当成假值替换掉
const wrong = payload.user?.prefs?.pageSize || 25;
console.log('with ||:', wrong);
// 可选调用与可选索引
const fn = payload.user?.greet?.();
console.log('call result:', fn);Output
Captured from a sandboxed run of this snippet in the build pipeline.
ada
undefined
undefined
pageSize: 0 theme: dark
with ||: 25
call result: undefinedHow it works
Module-level bindings hold the data — payload, pageSize, theme, wrong — with no function scope in between.
Applying it
Running the file prints labeled results such as pageSize:, with ||:, call result: — each operation’s effect is visible in the output.
Statements that matter
const pageSize = payload.user?.prefs?.pageSize ?? 25;
const theme = payload.user?.prefs?.theme ?? 'dark';
const fn = payload.user?.greet?.();
Interactive Tools for This Topic
FAQ
- Is a package install part of the setup?
- No. Installation is unnecessary because only built-in APIs are used. Its state lives in module-level bindings: `payload`, `pageSize`, `theme`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.