JavaScript Optional Chaining
By Flavio Copes
The optional chaining operator lets you safely read nested object properties and call methods without long && checks.
The optional chaining operator is a very useful operator which we can use to work with objects and their properties or methods. It arrived with ES2020, and every current browser and Node.js version supports it.
Have you ever used the && operator as a fallback? It’s one of my favorite JavaScript features.
In JavaScript, you can first check if an object exists, and then try to get one of its properties, like this:
const car = null
const color = car && car.color
Even if car is null, you don’t have errors and color is assigned the null value.
You can go down multiple levels:
const car = {}
const colorName = car && car.color && car.color.name
In some other languages, using && might give you true or false, since it’s usually a logic operator.
Not in JavaScript, and it allows us to do some cool things.
Optional chaining lets us write the same idea with less noise:
const color = car?.color
const colorName = car?.color?.name
If car is null or undefined, the result will be undefined.
And no errors, while a plain car.color on a null car would throw TypeError: Cannot read properties of null (reading 'color').
One thing ?. does not protect you from is a variable that was never declared. If there is no car at all, car?.color still throws ReferenceError: car is not defined.
It also works for calling a method, or reading a dynamic key, when the left side might be missing:
car?.start?.()
car?.['color']
If start is not there, car?.start?.() just returns undefined instead of throwing.
Pair it with nullish coalescing
Optional chaining often sits next to nullish coalescing: you read a nested value, and if the chain stops you fall back to a default:
const colorName = car?.color?.name ?? 'unknown'
?. returns undefined when something is missing, and ?? replaces that with 'unknown'. Unlike ||, the ?? operator only kicks in for null and undefined, so a 0 or an empty string is kept as it is.
One gotcha
Optional chaining short-circuits only on null and undefined. An empty string, 0 or false is not nullish, so the chain keeps going:
const label = ''
const length = label?.length
// length is 0, not undefined
That is usually what you want, and it’s also where ?. differs from the && trick, which stops on any falsy value. Just don’t treat ?. as a check for “any empty value”.
Want me to talk about your product? You can sponsor this site.
Related posts about js: