References

Beginner-friendly references for web development, with live, editable examples.

The JavaScript Optional Chaining ?. operator

Operator JavaScript All modern browsers Updated
Quick answer

The optional chaining operator ?. safely reads a nested property: if the value before it is null or undefined, the whole expression returns undefined instead of throwing. user?.address?.city won't crash if user or address is missing. Pair it with ?? to supply a fallback.

Overview

Optional chaining, ?., lets you reach into nested data without the dreaded "Cannot read properties of undefined" error. Normally user.address.city throws the moment user.address is undefined. Write user?.address?.city and instead of throwing, the expression simply short-circuits to undefined as soon as it hits a null or undefined link.

It works in three places: property access (obj?.prop), dynamic keys (obj?.[key]), and method calls (obj.method?.(), which calls the method only if it exists). That last form is great for optional callbacks — options.onClick?.() runs the handler if one was provided and does nothing otherwise.

Its perfect partner is the nullish coalescing operator: user?.name ?? "Guest" reads the name safely and falls back to "Guest" if anything along the way was missing. One caution — don't overuse it to paper over data that should always be there; reaching for ?. on every access can hide real bugs. Use it where a value is genuinely, legitimately optional.

Syntax

obj?.prop          // property
obj?.[key]         // dynamic key
obj.method?.()     // call only if it exists

user?.address?.city          // undefined if any link is missing
user?.name ?? "Guest"        // with a fallback

Example

Live example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
  const user = { name: 'Ada' }; // no address

  const city = user?.address?.city ?? 'Unknown';

  document.getElementById('out').textContent =
    'name: ' + user?.name + '\n' +
    'city: ' + city; // name: Ada / city: Unknown
</script>

Best practices

  • Use ?. where a value is genuinely optional, to avoid "cannot read properties of undefined" errors.
  • Combine it with ?? to provide a default: obj?.x ?? fallback.
  • Call optional methods or callbacks with fn?.() — it runs only if the function exists.
  • Don't sprinkle it everywhere — overusing it can mask data shape bugs that you'd rather catch.

Frequently asked questions

What does ?. do in JavaScript?
It safely accesses a nested property: if the value before it is null or undefined, the expression returns undefined instead of throwing an error.
How do I avoid "cannot read properties of undefined"?
Use optional chaining: obj?.nested?.value stops and returns undefined as soon as a link is missing.
How do I call a method only if it exists?
Use obj.method?.() — it invokes the method only when it's defined, and is undefined otherwise.
How do I give a default with optional chaining?
Combine it with ??: user?.name ?? "Guest".