Learn JavaScript
❯ operators.nullish_optional

Nullish Coalescing (??) & Optional Chaining (?.) in JavaScript

$concept

Modern JavaScript's two safety operators: ?? defaults only on null/undefined (count ?? 10 keeps legitimate 0, unlike ||), and ?. short-circuits property access (user?.address?.city yields undefined instead of throwing on missing links). Together they replaced mountains of && guards and ternary defaults.

Rules that matter: ?? cannot mix unparenthesized with && /|| (syntax error forcing explicit grouping), ?. short-circuits the entire rest of the chain (a?.b.c() skips the call too), and ?. works for calls (fn?.()) and brackets (m?.[k]) as well as dots.

$how it works
1

?? defaults narrowly

count ?? 10 keeps 0 and "" β€” only null/undefined fall through, unlike ||'s broad falsy net.

2

?. skips missing links

user?.address?.city evaluates to undefined when any link is nullish β€” no TypeError, no manual guards.

3

Short-circuits everything after

a?.b.c() skips property AND call when a is nullish β€” the whole tail vanishes safely.

4

No unparenthesized mixing

a ?? b || c is a syntax error β€” group explicitly ((a ?? b) || c) so precedence is always visible.

$example
let user = { name: "Ada" };
console.log(user?.name, user?.address?.city ?? "unknown");
console.log(0 ?? 99, 0 || 99);
Output
Ada unknown
0 99
1user?.name reads through safely (Ada); the missing address chain yields undefined, defaulted to unknown.
2?? preserves the legitimate 0 while || replaces it β€” the operators' core contrast in one line.
3Modern null-safety with zero manual guards.
$use cases
Defaulting config/props with ?? instead of ||
Drilling API responses (data?.user?.email) without guard pyramids
Optional calls (cb?.()) and dynamic keys (map?.[k])
Parenthesizing every ?? / && / || combination explicitly

Recommended resourcesAffiliate links Β· may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice β€” pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from β€” great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself β€” building beats watching.