Skip to content

Nullish Coalescing

In one line

The nullish coalescing operator (??) returns the right side when the left is null or undefined, otherwise the left.

In simple words

The nullish coalescing operator (??) is a way to provide a default value only when the left side is null or undefined. It is like the || operator but stricter: || treats 0, "", and false as falsy and falls through, while ?? only falls through on null and undefined.

This matters when 0 or "" is a valid value. For example, count || 10 returns 10 if count is 0 (probably wrong), but count ?? 10 returns 0 (correct — 0 is a real count). Use ?? when you want a default for missing values but want to keep other falsy values.

?? was added in ES2020 alongside optional chaining. You cannot mix ?? with || or && without parentheses (it throws a syntax error) to avoid ambiguity about precedence.

Example

javascript
const count = 0;
console.log(count || 10);  // 10 — wrong! 0 is a valid count
console.log(count ?? 10);  // 0  — correct, 0 is kept

const name = "";
console.log(name || "Anonymous"); // "Anonymous" — empty string replaced
console.log(name ?? "Anonymous"); // "" — empty string kept

const config = null;
console.log(config ?? { default: true }); // { default: true }

|| replaces any falsy value (0, "", false). ?? only replaces null and undefined, preserving 0 and empty strings.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary