TypeScript Lessons
A collection of useful TypeScript concepts and patterns.
Nullish Coalescing Operator (??)
The nullish coalescing operator (??) is a logical operator that returns the right-hand operand when the left-hand operand is null or undefined. Otherwise, it returns the left-hand operand.
Syntax
typescript
const result = leftOperand ?? rightOperandHow It Differs from || (Logical OR)
The key difference between ?? and || is what they consider "falsy":
| Operator | Returns right side when left is... |
|---|---|
|| | Any falsy value (false, 0, "", null, undefined, NaN) |
?? | Only null or undefined |
Examples
typescript
// Using ?? (nullish coalescing)
const count = 0
const result1 = count ?? 10 // result1 = 0 (0 is NOT nullish)
const name = ''
const result2 = name ?? 'default' // result2 = "" (empty string is NOT nullish)
const value = null
const result3 = value ?? 'fallback' // result3 = "fallback" (null IS nullish)
const data = undefined
const result4 = data ?? 'fallback' // result4 = "fallback" (undefined IS nullish)typescript
// Compare with || (logical OR)
const count = 0
const result1 = count || 10 // result1 = 10 (0 is falsy!)
const name = ''
const result2 = name || 'default' // result2 = "default" (empty string is falsy!)When to Use ??
Use the nullish coalescing operator when you want to:
- Preserve valid falsy values like
0,"", orfalse - Provide defaults only for missing values (
nullorundefined) - Handle optional properties in objects
typescript
interface UserSettings {
fontSize?: number
darkMode?: boolean
nickname?: string
}
function applySettings(settings: UserSettings) {
// Use ?? to preserve valid values like 0, false, or ""
const fontSize = settings.fontSize ?? 16 // Default 16 only if undefined
const darkMode = settings.darkMode ?? true // Default true only if undefined
const nickname = settings.nickname ?? 'User' // Default "User" only if undefined
// If we used || instead:
// fontSize of 0 would become 16 (wrong!)
// darkMode of false would become true (wrong!)
// nickname of "" would become "User" (might be wrong!)
}Combining with Optional Chaining (?.)
The nullish coalescing operator pairs well with optional chaining:
typescript
interface User {
profile?: {
bio?: string
}
}
const user: User = {}
// Safely access nested property and provide default
const bio = user.profile?.bio ?? 'No bio provided'Short-Circuit Evaluation
Like other logical operators, ?? short-circuits. If the left operand is not nullish, the right operand is never evaluated:
typescript
const value = 'exists'
const result = value ?? expensiveComputation() // expensiveComputation() is never called