Skip to content
Tutorials Center
My learning

Topics

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.

JavaScript
obj?.prop
obj?.[expression]
func?.(args)

Try it

JS Safe property access

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Short-circuiting and defaults

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
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, once a is nullish, .b, .c and .d are all skipped. If a exists but a.b is undefined, then .c throws, so add another ?. where a link in the chain can be missing.
  • Only null and undefined trigger it. 0, "" and false continue down the chain (and give undefined for 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 passes this correctly.
  • Undeclared variables: ?. does not help with names that were never declared. missing?.x still throws a ReferenceError.
  • 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.