
The Setup: the “default value” pattern
A very common line of JavaScript looks harmless:
const display = userInput || 'Guest';
The intent: “if the user gave us nothing, fall back to 'Guest'.” For strings and objects this mostly works — but the moment your real data is one of JavaScript’s falsy values, the pattern silently lies to you.
The Trap: || treats 0 and '' as “missing”
|| returns its right operand whenever the left operand is falsy. In JavaScript, falsy means not just null/undefined — it also includes 0, '' (empty string), NaN, and false. So:
function formatPrice(price) {
return price || '$0'; // ❌ bug waiting to happen
}
formatPrice(0); // '$0' <- wrong, the item really costs 0
formatPrice(42); // '42' <- fine
formatPrice(NaN); // '$0' <- maybe fine, but you lost the signal
function label(count) {
return count || 'none'; // ❌ a count of 0 now reads "none"
}
label(0); // 'none' <- misleading
This is one of the most common real-world bugs in forms, charts, and API responses: legitimate zeros and empty strings get swallowed by a fallback that was only meant for “no value at all.”
The Fix: ?? only catches null and undefined
The nullish coalescing operator (??) was added precisely for this. It returns the right operand only when the left is null or undefined — and leaves 0, '', NaN, and false completely alone:
function formatPrice(price) {
return price ?? '$0'; // ✅ correct intent
}
formatPrice(0); // 0 <- kept
formatPrice(null); // '$0' <- real fallback
formatPrice(undefined); // '$0' <- real fallback
function label(count) {
return count ?? 'none';
}
label(0); // 0 <- correct, not "none"
A quick cheat-sheet
a || b→bwhenais falsy (0,'',NaN,false,null,undefined)a ?? b→bonly whenaisnullorundefined- Prefer
??whenever the fallback means “no value provided.”
Gotcha: ?? can’t mix with ||/&& without parentheses
You cannot write a || b ?? c — JavaScript throws a SyntaxError because the precedence is ambiguous:
const x = null || undefined ?? 'fallback'; // ❌ SyntaxError
const y = (null || undefined) ?? 'fallback'; // ✅ 'fallback'
const z = a ?? b || c; // ❌ SyntaxError too — wrap explicitly
When to still use ||
|| is still the right tool when you genuinely want “any falsy value counts as missing” — e.g. normalizing a flag where false, 0, and '' should all collapse to a default:
const volume = settings.volume || 50; // 0 would also get the default — fine here
But for numeric, string, or boolean inputs that have a real zero/empty meaning, reach for ??.
Takeaway
||= “falsy fallback” (swallows0,'',NaN,false).??= “null/undefined fallback” (preserves0,'',NaN,false).- Use
??for default-value patterns on user data; keep||for cases where every falsy value really should be replaced. - Remember the parentheses rule when combining them.