Skip to content

Nullish Coalescing

In one line

The nullish coalescing operator (??) returns the right side only if the left is null or undefined, unlike || which checks all falsy values.

In simple words

The nullish coalescing operator (??) provides a default value for null or undefined. x ?? fallback returns x if x is not null/undefined, otherwise returns fallback. It only checks for null and undefined — not 0, empty string, or false.

This differs from the || operator, which checks all falsy values. 0 || 5 returns 5 (because 0 is falsy), but 0 ?? 5 returns 0 (because 0 is not nullish). This is important when 0 or "" are valid values.

Nullish coalescing is available in TypeScript 3.7+ and is standard JavaScript (ES2020). It is commonly used with optional chaining: config.timeout ?? 3000.

Example

typescript
const count = 0;
console.log(count || 10);  // 10 (0 is falsy)
console.log(count ?? 10);  // 0 (0 is not nullish)

const name = "";
console.log(name || "Anonymous"); // "Anonymous"
console.log(name ?? "Anonymous"); // ""

?? only falls back for null/undefined, preserving valid falsy values like 0 and ''.

Related terms

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