JavaScript Reference ยท Operators
The ?. operator
Reference for JavaScript optional chaining ?.: safe property access, optional method calls and bracket access, short-circuiting and what it cannot do.
Optional chaining (?.) reads a property, calls a method, or indexes into a value only if the value before it is not null or undefined. If it is, the whole chain stops and evaluates to undefined instead of throwing a TypeError.
obj?.prop
obj?.[expression]
func?.(args)
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
a?.b // property access a?.[expr] // computed access a?.(args) // call, only if a is not nullish a?.b.c.d() // the rest of the chain is skipped when a is nullish
| Form | Description |
|---|---|
a?.b |
undefined if a is null or undefined, otherwise a.b. |
a?.[x] |
undefined if a is nullish, otherwise a[x]. |
a?.() |
undefined if a is nullish, otherwise calls a(). |
Return value: the value of the chain, or undefined when it short-circuits.
Exceptions: you cannot assign through it (a?.b = 1 is a SyntaxError), and you cannot use it with a template literal tag or with new (new a?.b() is a SyntaxError). If the left side is not nullish, normal errors still occur: a?.() throws a TypeError if a is not a function.
Usage notes
- Short-circuit covers the whole chain. In
a?.b.c.d, onceais nullish,.b,.cand.dare all skipped. Ifaexists buta.bisundefined, then.cthrows, so add another?.where a link in the chain can be missing. - Only
nullandundefinedtrigger it.0,""andfalsecontinue down the chain (and giveundefinedfor missing properties). - Combine with
??for a fallback value. - Don't overuse it. Optional chaining on a value that must exist hides bugs; let it throw there.
- Calling methods:
obj.method?.()skips the call if the method is missing, and still passesthiscorrectly. - Undeclared variables:
?.does not help with names that were never declared.missing?.xstill throws aReferenceError. - Evaluation order: the left side is evaluated once, even in a long chain.
Browser support
Supported in current browsers (ES2020). It cannot be polyfilled, because it is syntax, so older environments need a build step; check a compatibility table for your targets.