Chapter IV · Operators & Expressions

Optional Chaining

The ?. operator safely accesses a nested property or calls a method, short-circuiting to undefined instead of throwing if anything along the way is null or undefined.

01 What Is Optional Chaining?

Before ES2020, reading a deeply nested property required chained manual checks: user && user.address && user.address.city. ?. exists to replace that boilerplate with one readable expression, for the very common case of optional or not-yet-loaded data.

02 Simple Example

Safe access into a possibly-missing nested object.

optional-chaining.js
const user = { profile: null };
console.log(user.profile?.email); // undefined, no error
console.log(user.profile.email);  // TypeError: Cannot read properties of null

03 How It Works

At each ?. link in the chain, the engine checks whether the value so far is null or undefined. If so, it stops immediately and the whole expression evaluates to undefined — no error thrown, and nothing further in the chain is evaluated. It also works for method calls (obj.method?.()) and array/bracket access (obj?.[key]).

04 Production Example

Reading a possibly-missing nested field from an API response, and safely calling an optional callback.

api-response.js
function getShippingCity(apiResponse) {
  return apiResponse?.order?.shippingAddress?.city ?? 'Unknown';
}

function runCallback(options) {
  options.onSuccess?.(); // calls it only if it exists
}

05 Mental Model

"A hiker checking each stepping stone before putting weight on it — the moment one is missing, they stop and report 'no path,' instead of falling through."

06 Common Mistakes

  • Overusing ?. everywhere can mask real bugs — if a property should always exist, a missing value is worth an error, not a silent undefined.
  • Pairing it with ?? (as in the API example) is the idiomatic way to get a safe access and a sensible fallback in one line.

07 Interview Questions

Q: What does user?.profile?.email evaluate to if user.profile is null?

undefined — the chain stops the moment it hits a null/undefined link, without throwing.

Q: Can optional chaining be used with method calls?

Yes — obj.method?.() calls the method only if it exists, otherwise evaluates to undefined instead of throwing a TypeError.

Key Takeaway

?. stops and returns undefined the moment it hits null/undefined in a chain, replacing manual guard checks — pair it with ?? for a clean default.

Related Concepts