How to use optional chaining in JavaScript

· Category: JavaScript

Short answer

Optional chaining ?. short-circuits and returns undefined if the left-hand side is null or undefined, making nested property access safe and concise.

Steps

  1. Access nested properties: javascript const city = user?.address?.city;
  2. Call optional methods: javascript const result = obj?.getValue?.();
  3. Combine with nullish coalescing: javascript const name = user?.name ?? "Anonymous";
  4. Use with bracket notation: javascript const key = "id"; const id = user?.[key];

Tips

  • Optional chaining only checks null or undefined, not other falsy values.
  • It short-circuits the entire remaining expression.

Common issues

  • Overusing optional chaining can hide errors that you actually want to catch.
  • obj?.foo.bar returns undefined if obj is null, but then accessing .bar on undefined throws if not chained further.