0Pricing
TypeScript Academy · Lesson

Nullish Coalescing with ??

Provide fallbacks only for null and undefined, not all falsy values.

The Nullish Coalescing Operator

The ?? operator returns its right-hand side only when the left-hand side is null or undefined. Otherwise it returns the left-hand value. It's the precise way to supply defaults.

const name: string | null = null;
const display = name ?? 'Guest';
console.log(display); // 'Guest'

Only Nullish Triggers the Fallback

The key word is nullish: only null and undefined cause the right-hand side to be used. Every other value — including falsy ones — passes through unchanged.

console.log(0 ?? 99);       // 0
console.log('' ?? 'x');     // ''
console.log(false ?? true); // false
console.log(null ?? 'def'); // 'def'

All lessons in this course

  1. Optional Chaining with ?.
  2. Nullish Coalescing with ??
  3. Combining ?. and ??
  4. Optional Calls and Element Access
← Back to TypeScript Academy