Chapter IV · Operators & Expressions
Nullish Coalescing
The ?? operator returns its right-hand side only when the left side is null or undefined — unlike ||, it leaves 0, "", and false alone.
01 What Is Nullish Coalescing?
Introduced in ES2020, ?? exists to fix a specific, common bug: using || for default values also overrides legitimate falsy data like 0 quantity or an empty string. ?? checks for exactly two things — null and undefined — and nothing else.
02 Simple Example
?? preserving 0 where || would have overwritten it.
let stock = 0;
console.log(stock || 10); // 10 — WRONG, 0 was a real value
console.log(stock ?? 10); // 0 — correct, 0 is not nullish
03 How It Works
a ?? b checks only whether a is strictly null or undefined. If so, it evaluates and returns b; otherwise it returns a as-is, whatever falsy-but-meaningful value it might be. Like && and ||, it short-circuits — the right side is never evaluated unless needed.
?? follows the same short-circuit shape as && and ||, testing for null/undefined specifically.
04 Production Example
Applying configuration defaults without clobbering intentional zero or empty-string values.
function createPagination(options) {
const pageSize = options.pageSize ?? 20;
const offset = options.offset ?? 0; // stays 0, not forced to a default
return { pageSize, offset };
}
05 Mental Model
"A form that only asks 'is this field literally blank?' — not 'is this field falsy in general.'"
06 Best Practice
Reach for ?? whenever a default is meant to fill in genuinely missing data, and reserve || for cases where every falsy value really should be treated the same.
07 Interview Questions
Q: Why would you choose ?? over || for a default value?
?? only falls back on null/undefined, so meaningful falsy values like 0, '', or false pass through untouched — || would incorrectly override them.
Key Takeaway
?? only treats null and undefined as "missing" — the safer choice for defaults whenever 0, "", or false could be legitimate values.