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
- Optional Chaining with ?.
- Nullish Coalescing with ??
- Combining ?. and ??
- Optional Calls and Element Access