optional chaining (?.)
In JavaScript, the optional chaining operator (?.) reads a property or calls a function only when the value on its left isn’t null or undefined. For either of those two values, the whole expression stops early and returns undefined instead of throwing a TypeError.
The check applies only to the value right before ?.. Any other value passes through, including 0, "", and false. Once a ?. short-circuits the expression, JavaScript skips the rest of the chain, along with any side effects in it. For example, user?.address.city returns undefined when user is null, but it still throws when user exists without an address.
JavaScript Optional Chaining Syntax
The optional chaining operator has three forms, for property access, computed keys, and function calls:
<object>?.<property>
<object>?.[<expression>]
<function>?.([<arguments>])
JavaScript Optional Chaining Examples
Say a user’s settings come from a profile where the theme section can be null. Optional chaining reads the nested values without a guard at each level:
> const settings = { theme: null, notify: { email: true } };
undefined
> settings.theme?.color
undefined
> const channel = "email";
undefined
> settings.notify?.[channel]
true
> settings.theme.color
Uncaught TypeError: Cannot read properties of null (reading 'color')
Because settings.theme is null, ?. returns undefined for .color. The computed form ?.[channel] reads settings.notify.email as usual, and the plain dot access on null throws.
A plugin object might define an onLoad hook but not an onSave hook. The ?.() form calls a hook only when it exists:
> const plugin = { name: "spellcheck", onLoad: (file) => `Loaded ${file}` };
undefined
> plugin.onLoad?.("draft.md")
'Loaded draft.md'
> plugin.onSave?.("draft.md")
undefined
> plugin.name?.()
Uncaught TypeError: plugin.name is not a function
The missing onSave hook returns undefined without a call. The last line shows that ?.() checks for null and undefined only. A property that holds a string still throws when called.
JavaScript Optional Chaining Gotchas
- An undeclared variable still throws a
ReferenceError, because evaluating the undeclared name throws before?.can check its value. A declared variable set toundefinedshort-circuits as expected. - An optional chain can’t be an assignment target, so
settings.theme?.color = "dark"is aSyntaxError. - Parentheses end the chain, so
(settings.theme?.color).lengththrows after?.returnsundefined.
JavaScript Optional Chaining Use Cases
- Reading nested fields from API responses where some levels are optional
- Calling optional callbacks and event hooks
- Looking up a computed key on an object that might be missing
- Supplying a fallback value together with the nullish coalescing operator (
??)
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.
By Leodanis Pozo Ramos • Updated Nov. 12, 2026