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

Nullish Coalescing with Assignment (??=)

Use the ??= operator to assign values only when variables are null or undefined.

Nullish Coalescing with Assignment (??=)

You'll learn: How to use the ??= operator to assign values only when variables are null or undefined, making default value assignment more concise.

The Core Idea

The nullish coalescing assignment operator (??=) combines the nullish coalescing operator (??) with assignment. It only assigns a new value to a variable if that variable is currently null or undefined. If the variable already has a value (even if it's 0, false, or an empty string), the assignment doesn't happen.

Think of it like a lazy default setter: "If you're nothing, become this. If you're something—even zero or false—stay as you are."

How It Works

let count = null;
count ??= 10;
console.log(count); // 10

let score = 0;
score ??= 100;
console.log(score); // 0 (not replaced!)

let name = undefined;
name ??= "Anonymous";
console.log(name); // "Anonymous"

let title = "";
title ??= "Untitled";
console.log(title); // "" (empty string is NOT nullish)

Why Use ??= Instead of Just ??

Before ??=, you'd write:

config.timeout = config.timeout ?? 3000;

With ??=, it's cleaner:

config.timeout ??= 3000;

The left-hand side (config.timeout) is only evaluated once, and the code clearly expresses intent: "ensure this variable has a value."

Practical Example

let settings = { retries: 0 };

settings.retries ??= 5;    // stays 0
settings.timeout ??= 3000; // becomes 3000 (was undefined)

console.log(settings); // { retries: 0, timeout: 3000 }

Key Takeaway: Use ??= to assign default values only when a variable is null or undefined, preserving falsy values like 0, false, and empty strings.