JavaScript Optional Chaining (?.) Explained with Examples | TryJS

Learn JavaScript optional chaining (?.) with runnable examples. Safely access nested properties, call optional methods, and index arrays without TypeErrors.

Overview

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.

How It Works

Property access: obj?.prop

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.

Method calls: obj?.method()

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.

Dynamic keys and arrays: obj?.[key], arr?.[0]

Optional chaining also works with computed access and array indexing. users?.[0]?.name walks through null-safe at every step.

Combines with nullish coalescing

user?.name ?? 'Anonymous' is the canonical pattern: safely navigate, then fall back when the result is null or undefined.

Common Mistakes

When to Use It

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.

Runnable Example

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.

Frequently Asked Questions

What is optional chaining in JavaScript?

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+.

Does optional chaining work on function calls?

Yes. obj.method?.() calls method only if it's not null/undefined. Useful for optional callbacks: props.onClick?.(event).

What is the difference between ?. and && for safe access?

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.

Can I use optional chaining with nullish coalescing?

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.