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

The ||= (Logical OR Assignment) Operator

Using ||= to assign a value only if the left operand is falsy, replacing the pattern `x = x || defaultValue`.

The ||= (Logical OR Assignment) Operator

You'll learn how ||= elegantly assigns a default value only when needed, replacing a common pattern with cleaner syntax.

What It Does

The ||= operator assigns a value to a variable only if that variable is falsy. It's shorthand for the pattern x = x || defaultValue, which you've likely written many times when setting defaults.

Think of it like a lazy initialization: "If you don't have a value yet, here's one for you. But if you already have something, keep it."

The Old Way vs. The New Way

Before ||=, you'd write:

let userName = '';
userName = userName || 'Guest';  // userName becomes 'Guest'

let theme = 'dark';
theme = theme || 'light';  // theme stays 'dark'

With ||=, it's more concise:

let userName = '';
userName ||= 'Guest';  // userName becomes 'Guest'

let theme = 'dark';
theme ||= 'light';  // theme stays 'dark'

How It Works

The operator checks if the left side is falsy (false, 0, '', null, undefined, NaN). If so, it assigns the right side. If not, nothing happens.

let count = 0;
count ||= 10;  // count becomes 10 (0 is falsy)

let name = null;
name ||= 'Anonymous';  // name becomes 'Anonymous'

let settings = { mode: 'easy' };
settings.difficulty ||= 'normal';  // Adds difficulty: 'normal'

When to Use It

Perfect for initializing optional configuration, setting fallback values, or ensuring objects have required properties without overwriting existing ones.

Key Takeaway: Use ||= to assign a default value only when the current value is falsy—it's the cleaner, more readable way to handle conditional initialization.