Nullish coalescing (??)
- Version
- es2025
- Since
- es2020
- Review
- Draft
Summary#
left ?? right evaluates the fallback only when the left side is null or undefined. Use it when 0, an empty string, or false is a valid supplied value.
Syntax#
const value = input ?? fallback;
Example#
function retryCount(configured: number | null): number {
return configured ?? 3;
}
console.log(retryCount(0));
console.log(retryCount(null));
Expected output#
0
3
Common mistakes#
value || fallback treats any falsy value as missing. Group explicitly when mixing ?? with && or ||, since JavaScript disallows those combinations without parentheses.
Version applicability#
ES2020 standardized ??. TypeScript 3.7 added the syntax with downlevel emit for older JavaScript targets.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0