Objects

JavaScript Optional Chaining

The optional chaining operator is a very useful operator which we can use to work with objects and their properties or methods

The optional chaining operator (?.) reads nested properties without throwing when something in the chain is missing.

Before optional chaining, I often guarded access with &&:

const car = null
const color = car && car.color

If car is null, the expression stops and color becomes that falsy value. No error.

Go deeper:

const car = {}
const colorName = car && car.color && car.color.name

Optional chaining shortens the same idea:

const color = car?.color
const colorName = car?.color?.name

If car is null or undefined, the result is undefined. No TypeError.

Optional chaining also calls methods safely:

const result = user.getName?.()

If getName is missing, the call is skipped and the result is undefined.

Optional chaining also works with dynamic keys:

const key = 'color'
const value = car?.[key]

Array access supports the same pattern:

const first = list?.[0]

It does not replace validation everywhere. If missing data is exceptional, throw or return early with a clear error instead of silently producing undefined deep in the call stack.

?. only stops on null or undefined. It does not treat 0 or '' as missing.

Combine optional chaining with nullish coalescing when you need a default after a safe read:

const theme = settings?.theme ?? 'light'

Optional chaining short-circuits left to right. The first null or undefined stops the chain and yields undefined.

Be careful with expressions on the left of ?. that have side effects. They still run even when the chain eventually yields undefined.

Optional chaining works in assignment with ??= and friends only when the language syntax allows it. For most reads, combine ?. with ?? for defaults.

I still use && guards when I need falsy values like 0 or '' to stop the chain. Optional chaining only treats null and undefined as absent.

Try const car = {} then read car?.color?.name and car.color.name side by side. The first returns undefined. The second throws.

Lesson completed