Skip to content

Optional Chaining

The optional chaining operator ?. reads a property only if the value before it exists. If that value is null or undefined, the expression stops and gives undefined instead of throwing a TypeError. It arrived in ES2020 and works in every current browser and in Node.js.

const users = [
{ name: 'Ana', address: { city: 'Leeds' } },
{ name: 'Ben' },
];
for (const user of users) {
console.log(user.name, user.address?.city);
}
try {
console.log(users[1].address.city);
} catch (error) {
console.log(error.name + ': ' + error.message);
}

This prints:

Ana Leeds
Ben undefined
TypeError: Cannot read properties of undefined (reading 'city')

Ben has no address, so user.address is undefined. With a plain dot, reading city from undefined throws. With ?., the expression gives undefined and the loop carries on.

Before ?., the same guard was written with &&, as in user.address && user.address.city, which repeats the path at every level and also stops at other falsy values such as 0 and ''.

?. works for property names, for bracket access and for function calls:

  • obj?.prop reads a property.
  • obj?.[key] reads a property by a computed key or an array index.
  • func?.() calls a function only if it exists.
const library = {
shelves: [{ books: ['Emma', 'Persuasion'] }],
describe() {
return 'A small library';
},
};
console.log(library.shelves?.[0]?.books?.[1]);
console.log(library.shelves?.[3]?.books?.[1]);
console.log(library.describe?.());
console.log(library.catalogue?.());

This prints:

Persuasion
undefined
A small library
undefined

library.catalogue does not exist, so ?.() skips the call. ?.() guards only against null and undefined: calling a property that exists but is not a function, such as a string, still throws a TypeError.

When ?. stops, it skips everything after it in the same chain, including function calls inside brackets:

let calls = 0;
const nextId = () => ++calls;
const record = null;
console.log(record?.items[nextId()]);
console.log(calls);

This prints:

undefined
0

The .items[...] after record?. is never worked out, so nextId is not called. This is also why record?.items[0] needs no second ?. before [0]: if record is null, the whole chain stops. A second ?. is needed only where items itself may be missing.

?. gives undefined when something is missing, and the nullish coalescing operator ?? replaces undefined with a default:

const user = { name: 'Ben' };
const city = user.address?.city ?? 'No city given';
console.log(city);

This prints:

No city given
  • ?. cannot be the target of an assignment. user?.name = 'Ana' is a SyntaxError: Invalid left-hand side in assignment.
  • Use it only where a value is genuinely allowed to be missing. Scattering ?. over values that should always exist hides bugs, because a mistake then gives undefined instead of an error at the line that caused it.
  • The variable at the start of the chain must be declared. notDeclared?.prop still throws a ReferenceError.

Steve Griffith covers this topic in his video Optional Chaining New ES2020 Feature.