Course contentsShow
← JavaScript
Lesson 1948 of 2,72341. Modern JavaScript Features (ES2020+)Free lesson

Nullish vs Falsy Values

Learn why ?? only checks for null/undefined, not all falsy values like 0, '', or false.

Nullish vs Falsy Values

You'll learn why the nullish coalescing operator (??) is more precise than logical OR (||) by only treating null and undefined as "missing" values.

The Crucial Difference

JavaScript has falsy values: false, 0, '' (empty string), NaN, null, and undefined. These all evaluate to false in boolean contexts.

But "falsy" and "nullish" aren't the same thing. Nullish values are only null and undefined — values that represent the absence of a value. The other falsy values (0, false, '') are legitimate, intentional values that you might actually want to use.

This is where ?? shines: it only substitutes a default when the left side is null or undefined, not when it's any other falsy value.

// Using || (checks for ANY falsy value)
const count = 0;
const display = count || 10;
console.log(display); // 10 — Oops! We wanted 0

const name = '';
const greeting = name || 'Guest';
console.log(greeting); // "Guest" — But '' might be intentional

// Using ?? (checks ONLY for null/undefined)
const count2 = 0;
const display2 = count2 ?? 10;
console.log(display2); // 0 — Perfect!

const name2 = '';
const greeting2 = name2 ?? 'Guest';
console.log(greeting2); // '' — Preserves empty string

const score = null;
const finalScore = score ?? 100;
console.log(finalScore); // 100 — Replaces null as expected

Think of it like asking "Is this variable unassigned?" (??) versus "Is this variable not truthy?" (||). The first question is much more specific.

Key Takeaway: Use ?? when you want to provide defaults only for null or undefined, preserving other falsy but valid values like 0, false, or ''. Use || only when you genuinely want to replace all falsy values.