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.
Reading a property that may be missing
Section titled “Reading a property that may be missing”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 LeedsBen undefinedTypeError: 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 ''.
Three forms
Section titled “Three forms”?. works for property names, for bracket access and for function calls:
obj?.propreads 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:
PersuasionundefinedA small libraryundefinedlibrary.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.
The rest of the chain is skipped
Section titled “The rest of the chain is skipped”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:
undefined0The .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.
Pairing with ??
Section titled “Pairing with ??”?. 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 givenLimits
Section titled “Limits”?.cannot be the target of an assignment.user?.name = 'Ana'is aSyntaxError: 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 givesundefinedinstead of an error at the line that caused it. - The variable at the start of the chain must be declared.
notDeclared?.propstill throws aReferenceError.
Steve Griffith covers this topic in his video Optional Chaining New ES2020 Feature.