Optional Chaining, Nullish Coalescing, and Logical Assignment
`?.` for safely reading a chain that might be `null`, `??` for defaulting only on missing values (not every falsy one), and the `||=`/`&&=`/`??=` operators.
Optional Chaining, Nullish Coalescing, and Logical Assignment
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- `?.` short-circuits a property, method, or index access the moment it hits a `null` or `undefined` value: `user?.address?.city` evaluates to `undefined` instead of throwing, the first time any link in the chain turns out to be missing.
- `??` returns its right-hand side only when the left side is specifically `null` or `undefined` — not for every falsy value the way `||` does, which is why `count ?? 0` and `count || 0` behave differently the moment `count` is a legitimately valid `0`.
- `||` treats `0`, `""`, `false`, and `NaN` as reasons to fall back to the default, because all of those are falsy; `??` treats only `null`/`undefined` that way, which makes it the correct choice whenever a falsy-but-valid value should be left alone.
- `||=`, `&&=`, and `??=` combine a logical check with an assignment: `x ||= y` assigns only if `x` is currently falsy, `x &&= y` assigns only if `x` is currently truthy, and `x ??= y` assigns only if `x` is currently `null` or `undefined` — each replaces a longer `if` statement that would otherwise test `x` before deciding whether to touch it.
- `?.` and `??` are frequently chained together — `user?.profile?.bio ?? "No bio yet"` safely reads through a possibly-missing chain and then supplies a default only if what comes out the other end is actually missing, not just falsy.
The chain that used to need a guard clause
Reading a nested value off an object you don’t fully control — an API response, a config object with optional fields — used to mean writing a guard for every link that might be missing:
const city = user && user.address && user.address.city;
Miss one of those && checks and a missing address throws a
TypeError: Cannot read properties of undefined, usually from somewhere
far away from where the actual data went missing. Optional chaining
collapses that whole guard into the access itself:
const city = user?.address?.city;
Each ?. checks the value immediately to its left. If that value is
null or undefined, the entire expression short-circuits right there
and evaluates to undefined — the rest of the chain never runs, so it
can’t throw trying to read a property off something that doesn’t exist.
?. also works before a function call (user.greet?.(), which skips the
call if greet doesn’t exist) and before a computed index
(list?.[0]).
Why ?? exists when || already does defaulting
Before ??, a common way to supply a fallback value was ||:
const timeout = userTimeout || 3000;
This looks right until userTimeout is deliberately 0 — meaning “no
delay, fire immediately” — and || throws that intent away, because 0
is falsy and || falls back to 3000 regardless of whether the original
value was missing or just falsy. The same trap catches an empty
string meant as “no label” or a false meant as “explicitly turned off.”
?? — the nullish coalescing operator — checks for one specific thing
instead of general falsiness: is the left side null or undefined?
Nothing else counts.
const timeout = userTimeout ?? 3000;
Now 0, "", and false all pass through untouched, because none of
them are null or undefined — only an actually-missing userTimeout
triggers the fallback. The rule of thumb: reach for ?? whenever a
falsy-but-meaningful value needs to survive, which in practice is most of
the time you’re defaulting a value that didn’t come from a boolean
context to begin with.
Logical assignment: folding the check into the assignment
||=, &&=, and ??= are shorthand for a pattern you’d otherwise write
as an if statement guarding a plain assignment. Each one only assigns
under a specific condition, matching its non-assignment counterpart:
x ||= y; // same idea as: if (!x) x = y; — assign if x is falsy
x &&= y; // same idea as: if (x) x = y; — assign if x is truthy
x ??= y; // same idea as: if (x == null) x = y; — assign if x is null/undefined
The most common of the three in practice is ??=, used to fill in a
default only if a value was never set, without disturbing a legitimately
falsy value that was:
function configure(options = {}) {
options.retries ??= 3;
options.verbose ??= false;
return options;
}
If someone explicitly passes verbose: false, ??= leaves it as false
— the same mistake ||= would make here by overwriting it with the
default the moment it saw a falsy value.
Where this fits
All three features build directly on
equality and comparison:
?? and ??= only make sense once you’ve internalized that null and
undefined are the two values JavaScript treats as “nothing here,” and
that treating them differently from the rest of the falsy values is a
deliberate, narrower check than || performs. Together, these three
features are some of the most-used modern syntax in everyday JavaScript —
short enough to miss if you’re skimming code, but worth recognizing on
sight, since each one is quietly replacing a longer, more error-prone
pattern from before it existed.
Check yourself
What does `user?.address?.city` evaluate to if `user.address` is `undefined`, and why doesn't this throw a TypeError?
It evaluates to `undefined`. The `?.` before `.city` checks `user.address` first; the moment it finds `undefined`, it stops right there and returns `undefined` for the whole expression instead of trying to read `.city` off of `undefined`, which is exactly the read that would otherwise throw.
`let count = 0; const shown = count || 10;` sets `shown` to `10`. Why, and what would `count ?? 10` give instead?
`||` only cares whether `count` is truthy, and `0` is falsy, so `||` treats it as a reason to fall back to `10` even though `0` is a perfectly valid, intentional value here. `count ?? 10` checks specifically for `null`/`undefined`, and `0` is neither, so it would correctly return `0` and leave the real value alone.
What's the difference in behavior between `x ||= y` and `x ??= y` when `x` currently holds `false`?
`x ||= y` assigns `y` to `x`, because `||=` triggers whenever `x` is falsy, and `false` is falsy. `x ??= y` does nothing and leaves `x` as `false`, because `??=` only triggers when `x` is `null` or `undefined` — and a deliberately-set `false` is neither, so it's treated as an already-valid value worth keeping.
How would you rewrite `if (!cache[key]) { cache[key] = computeValue(); }` using a logical assignment operator?
`cache[key] ||= computeValue();` — it assigns `computeValue()` to `cache[key]` only when `cache[key]` is currently falsy (missing, `undefined`, or any other falsy placeholder), which is exactly what the `if` check was doing, just folded into one line.
Why does it make sense that `?.` and `??` are often used together, as in `settings?.theme ?? "light"`?
They solve two different halves of the same problem. `?.` protects the read itself — it stops a crash if `settings` or an earlier link in the chain doesn't exist. `??` then decides what to do with whatever that safe read produced — if it came out as `null`/`undefined` (either because it was never set, or because `?.` itself returned `undefined` after short-circuiting), `??` supplies the fallback; if it came out as a real, falsy-but-valid value, `??` leaves it alone.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.