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

The ??= (Nullish Coalescing Assignment) Operator

Using ??= to assign a value only if the left operand is null or undefined, avoiding falsy false positives.

The ??= (Nullish Coalescing Assignment) Operator

What you'll learn: How to use ??= to assign a value only when a variable is null or undefined, avoiding unwanted overrides of falsy values like 0 or "".

The Core Idea

The nullish coalescing assignment operator (??=) combines the nullish coalescing operator (??) with assignment. It assigns a value to a variable only if that variable is currently null or undefined. Unlike ||=, which assigns on any falsy value, ??= respects intentional falsy values like 0, false, or empty strings.

Think of it as a safety check: "If this variable truly has no value (null/undefined), give it this default—but don't overwrite legitimate values, even if they're falsy."

How It Works

let count = 0;
count ??= 10; // count remains 0 (not nullish)

let total = null;
total ??= 10; // total becomes 10 (was nullish)

let name = "";
name ??= "Guest"; // name remains "" (not nullish)

let user = undefined;
user ??= "Anonymous"; // user becomes "Anonymous"

The Key Difference from ||=

// Using ||= (overwrites falsy values)
let score = 0;
score ||= 100; // score becomes 100 (0 is falsy)

// Using ??= (preserves falsy values)
let score = 0;
score ??= 100; // score remains 0 (0 is not nullish)

Common Pattern

This is especially useful for lazy initialization of configuration objects:

const config = {};
config.timeout ??= 5000;
config.retries ??= 3;
config.debug ??= false;
// Only assigns defaults if properties don't exist

Key Takeaway: Use ??= when you want to provide default values only for null or undefined, preserving intentional falsy values like 0, false, or "" that ||= would mistakenly overwrite.