What is optional chaining?

Optional chaining (?.) safely accesses a property, array item or method on something that might be null or undefined, returning undefined instead of throwing a TypeError.

The three forms

  • Property: user?.profile?.email
  • Bracket/array: matrix?.[row]?.[col], obj?.[dynamicKey]
  • Call: callback?.(), user.save?.() calls the method only if it exists.

How it short-circuits

As soon as the value on the left of a ?. is null or undefined, the whole rest of the chain is skipped and the expression returns undefined. Arguments of a skipped call are not evaluated either.

Pairs well with ??

user?.settings?.theme ?? "light" reads a deep value with a default in one line.

When not to use it

  • Do not sprinkle it everywhere. If a value must exist, a TypeError is a useful signal that something is wrong. Use ?. only where absence is a normal, expected case.
  • It does not protect against other errors: user?.name.toUpperCase() still throws if user exists but name is undefined. Each uncertain link needs its own ?..
  • It cannot be used on the left side of an assignment: user?.name = "x" is a syntax error.

Under the hood

a?.b is roughly a == null ? undefined : a.b, and the engine evaluates a only once.

Code example

js
1const users = [
2 { name: "Ada", profile: { email: "ada@example.com", tags: ["admin"] }, notify() { return "sent"; } },
3 { name: "Linus" }, // no profile, no notify method
4];
5
6for (const u of users) {
7 console.log(u.name, u.profile?.email ?? "no email", u.profile?.tags?.[0] ?? "no tags", u.notify?.() ?? "cannot notify");
8}
9// Ada ada@example.com admin sent
10// Linus no email no tags cannot notify
11
12// Without ?. this throws
13try {
14 users[1].profile.email;
15} catch (e) {
16 console.log(e.name); // TypeError
17}
18
19// Short-circuit: the call's argument is never evaluated
20let calls = 0;
21const missing = null;
22missing?.process(++calls);
23console.log(calls); // 0
24
25// Each uncertain link needs its own ?.
26const partial = { name: undefined };
27try {
28 partial?.name.toUpperCase();
29} catch (e) {
30 console.log("still throws:", e.name); // TypeError
31}
32console.log(partial?.name?.toUpperCase()); // undefined

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app