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

What is Nullish Coalescing?

Understand the ?? operator and how it differs from logical OR for handling null and undefined values.

What is Nullish Coalescing?

You'll learn how the ?? operator provides a safer default value mechanism than logical OR by only treating null and undefined as "missing."

The Problem with Logical OR

You've used || to provide fallback values:

const count = userInput || 10;

But || treats all falsy values (0, '', false, NaN, null, undefined) as "missing." This creates bugs when legitimate values are falsy:

const quantity = 0 || 5;  // 5 — but 0 was intentional!
const name = '' || 'Guest';  // 'Guest' — but empty string might be valid!

Enter the Nullish Coalescing Operator

The ?? operator only considers null and undefined as "nullish" — everything else passes through:

const quantity = 0 ?? 5;        // 0 (zero is NOT nullish)
const name = '' ?? 'Guest';     // '' (empty string is NOT nullish)
const active = false ?? true;   // false (false is NOT nullish)

const missing = null ?? 'default';      // 'default'
const unset = undefined ?? 'default';   // 'default'

When to Use Which

Use ?? when you want to distinguish between "no value provided" (null/undefined) and "a falsy value was intentionally provided" (0, false, '').

Use || when you genuinely want any falsy value to trigger the fallback.

// Good: respects explicit zero
const timeout = userTimeout ?? 3000;

// Good: accepts empty strings as valid
const label = userLabel ?? 'Untitled';

Key Takeaway: The nullish coalescing operator (??) provides default values only for null and undefined, avoiding the pitfalls of || treating all falsy values as missing.