Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 156 Β· Operators

Nullish Coalescing and Optional Chaining

Handle missing data safely in JavaScript with the ?? nullish coalescing operator and ?. optional chaining for properties, method calls and bracket access.

Real data is full of holes. An API response might leave out a field, a user might not have filled in their address, a settings object might be missing a whole section. Reading through such data used to mean long chains of checks like user && user.address && user.address.city, and picking defaults with || that accidentally threw away valid values like 0.

Two operators added in 2020 fix both problems. Nullish coalescing, ??, picks a default only when a value is truly missing. Optional chaining, ?., reads properties, calls methods and accesses elements without crashing when something along the way is missing. Together they make code that handles incomplete data short and safe.

What "nullish" means

A value is nullish if it is null or undefined β€” the two "no value" values from null and undefined. That's a narrower group than falsy: 0, "", false and NaN are falsy, but they are not nullish. They are real values that just happen to be "zero-ish".

Both operators in this lesson react to nullish values only. That's exactly what makes them safer than their older alternatives.

Nullish coalescing: ??

a ?? b returns a, unless a is null or undefined β€” then it returns b.

JS ?? versus ||

Press Run (or Ctrl + Enter) to see the console output here.

No output.

With ||, a quantity of 0, an empty note and an explicit false are all thrown away and replaced. With ??, they are kept; only null (the coupon) and undefined (the missing discount) fall back. As a rule of thumb in modern code:

  • Use ?? for default values β€” "if this wasn't provided, use that".
  • Use || only when every falsy value should be replaced, such as treating an empty search box the same as no search at all.

Like ||, ?? short-circuits: the right side is evaluated only if it's needed. And you can chain it to try several sources in order:

JavaScript
const theme = userSettings.theme ?? teamSettings.theme ?? "light";

Mixing ?? with && or ||

JavaScript refuses to guess how ?? should combine with && or || without parentheses, so this is a SyntaxError:

JavaScript
const value = a || b ?? c;    // SyntaxError
const value = (a || b) ?? c;  // OK: you said what you meant

The logical assignment form ??= assigns a default in place: settings.lang ??= "en".

Optional chaining: ?.

Reading a property of undefined or null throws a TypeError. That's what happens when you dig into nested data and one level is missing:

JavaScript
const user = { name: "TomΓ‘s" };   // no address
user.address.city;                // TypeError: Cannot read properties of undefined

The optional chaining operator ?. checks the value on its left. If it's nullish, the whole expression stops and returns undefined instead of throwing. Otherwise it continues as a normal property access:

JS Reading nested data safely

Press Run (or Ctrl + Enter) to see the console output here.

No output.

user?.address?.city reads like "the city, if there is a user and if they have an address". Compare it with the old version, user && user.address && user.address.city β€” longer, and it can return odd falsy values like "" or 0 instead of undefined.

Short-circuiting the whole chain

When ?. finds a nullish value, it skips everything after it in the same chain β€” further property reads, calls, even arguments that would have been computed:

JavaScript
const report = null;

report?.summary.title.toUpperCase();  // undefined β€” no error

Even though .title and .toUpperCase() use plain dots, they never run, because the chain stopped at report?.. You only need ?. at the points that can actually be missing.

The three forms of ?.

Optional chaining works for property names, bracket access and function calls:

Form Use it for If the left side is nullish
obj?.prop a property by name returns undefined
obj?.[expr] a computed key or array index returns undefined
fn?.(args) calling a function that may not exist returns undefined, doesn't call
JS ?.[] and ?.()

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Note that fn?.() only protects against fn being null or undefined. If fn exists but isn't a function β€” say it's a string β€” you still get a TypeError. That's usually what you want: it signals a real bug.

Combining ?. and ??

The two operators are a natural pair. ?. safely produces undefined when data is missing, and ?? turns that undefined into a sensible default:

JS Safe reads with defaults

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Look at brand: apiResponse.vendor is missing, so the chain stops before .brand and before .toUpperCase() would run, and ?? supplies the fallback. The firstReview line works the same way with an empty array: reviews[0] is undefined, so ?.text stops there.

Every line reads a value that might be missing and supplies a fallback, without a single if. And because ?? is used instead of ||, the free sample keeps its price of 0.

Using them wisely

These operators are so convenient that it's tempting to put ?. everywhere. Resist that. Each ?. says "it's normal for this to be missing" β€” and if that isn't true, you've hidden a bug:

JavaScript
// Too defensive: if config is ALWAYS loaded, a crash here is useful
const port = config?.server?.port ?? 3000;

// Better: only mark the genuinely optional part
const port = config.server.port ?? 3000;

When required data is missing, an early error with a clear message is much easier to debug than an undefined that travels through your program and breaks something far away. Use ?. where data is genuinely optional β€” user-entered fields, optional API properties, optional callbacks β€” and plain . everywhere else.

Two limits to know: you can't assign through optional chaining β€” user?.name = "Kim" is a SyntaxError. And ?. only works on values that exist as variables: undeclaredVariable?.x still throws a ReferenceError, because the problem is the name, not its value.

Check your understanding

Quick check Β· 4 questions

of 4 answered You scored / 4 Β· perfect!

  1. 1. What does 0 ?? 10 return?

    ?? only falls back for null and undefined. 0 is a real value, so it's kept.
  2. 2. Given const user = {}, what does user.profile?.avatar return?

    user.profile is undefined, so ?. stops the chain and returns undefined instead of throwing.
  3. 3. How do you call options.onClose only if it was provided?

    fn?.() checks the function itself before calling it. options?.onClose() would only protect against options being missing.
  4. 4. What happens with a || b ?? c?

    Mixing ?? with || or && without parentheses isn't allowed, so the intent is always explicit.

Summary

  • Nullish means null or undefined β€” narrower than falsy.
  • a ?? b returns b only if a is nullish, so 0, "" and false are kept; prefer it over || for defaults.
  • ?. stops a chain and returns undefined when the value before it is nullish; it works as obj?.prop, obj?.[key] and fn?.().
  • Combine them: data?.items?.[0]?.name ?? "None".
  • Use ?. only where data is genuinely optional, so real bugs still fail loudly. You can't assign through ?..

Next: Bitwise Operators.