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

Replacing || with ??

Identify when to migrate from logical OR to nullish coalescing to avoid bugs with falsy values.

Replacing || with ??

You'll learn when migrating from || to ?? prevents subtle bugs with legitimate falsy values.

The Problem with ||

For years, JavaScript developers used || (logical OR) for default values:

const port = config.port || 3000;

This worked—until it didn't. The || operator treats all falsy values (0, '', false, NaN) as "missing" and replaces them. But what if 0 or false are intentional values?

const volume = userSettings.volume || 50;
// Bug! If volume is 0 (muted), it becomes 50

Enter Nullish Coalescing

The ?? operator only replaces null or undefined—nothing else:

const volume = userSettings.volume ?? 50;
// 0 stays 0, false stays false
// Only null/undefined become 50

When to Migrate

Migrate from || to ?? when:

  • The value might legitimately be 0, '', or false
  • You're dealing with numeric settings, boolean flags, or empty strings
  • You only want to catch "not provided" cases

Keep || when:

  • You genuinely want to treat empty strings or 0 as "no value"
  • Legacy code depends on this behavior intentionally
// Before (buggy):
const retries = options.retries || 3; // 0 retries becomes 3!

// After (correct):
const retries = options.retries ?? 3; // 0 retries stays 0

The Migration Pattern

Think of it like asking different questions: || asks "is this truthy?", while ?? asks "does this exist?" Use ?? when existence—not truthiness—is what matters.

Key Takeaway: Replace || with ?? whenever 0, false, or '' are valid values you need to preserve, not bugs waiting to happen.