Learn JavaScript optional chaining (?.) with runnable examples. Safely access nested properties, call optional methods, and index arrays without TypeErrors.
Optional chaining (?.) is an ES2020 operator that short-circuits property access, method calls, and array indexing when the left-hand side is null or undefined. Instead of throwing a TypeError, the whole expression evaluates to undefined. It replaces the long chains of && guards you used to write for safe navigation through API responses and optional objects.
If obj is null or undefined, the expression short-circuits to undefined. Otherwise it proceeds as normal. Only null and undefined trigger the short-circuit — 0, '', and false do not.
The method call only happens if obj is not null/undefined. This is useful for optional callbacks: onClick?.(event) fires only if onClick was provided.
Optional chaining also works with computed access and array indexing. users?.[0]?.name walks through null-safe at every step.
user?.name ?? 'Anonymous' is the canonical pattern: safely navigate, then fall back when the result is null or undefined.
Use optional chaining when navigating data whose shape is genuinely optional — API responses with nullable fields, optional callback props, DOM query results. Don't use it as a blanket null-safety layer; that hides real bugs.
const user = {
name: "Alice",
address: {
city: "NYC",
},
logs: [{ ts: 1700000000, msg: "hello" }],
};
// Before: long && chain
const oldCity = user && user.address && user.address.city;
// With optional chaining
console.log(user?.address?.city); // "NYC"
console.log(user?.company?.name); // undefined (no throw)
console.log(user?.logs?.[0]?.msg); // "hello"
console.log(user?.logs?.[99]?.msg); // undefined
// Optional method call
const maybeCallback = undefined;
maybeCallback?.("ignored"); // safe, no-op
// Pair with nullish coalescing for defaults
const displayName = user?.profile?.name ?? "Anonymous";
console.log(displayName);
Open this example in the TryJS playground to edit and run the code instantly in your browser — no signup needed.
Optional chaining (?.) is an operator that short-circuits property access and method calls when the left-hand side is null or undefined, returning undefined instead of throwing. It was added in ES2020 and is supported in every modern browser and Node 14+.
Yes. obj.method?.() calls method only if it's not null/undefined. Useful for optional callbacks: props.onClick?.(event).
Both guard against null/undefined, but && also short-circuits on any falsy value (0, '', false). Optional chaining only short-circuits on null and undefined, which is usually what you actually want.
Yes, and it's the most common pattern: user?.profile?.name ?? 'Guest'. Optional chaining navigates safely, then ?? supplies a default when the result is null or undefined.