|| treats 0, ”, false as falsy. ?? only checks null/undefined.
Default values with || break when value is 0. Nullish coalescing (??) fixes this. Use ?? for default values.
❌ || (Bug with 0)
const volume = userVolume || 50; // If userVolume = 0 → volume = 50 (WRONG!) const name = userName || 'Guest'; // If userName = '' → name = 'Guest' (WRONG!)
✅ ?? (Correct)
const volume = userVolume ?? 50; // If userVolume = 0 → volume = 0 (CORRECT!) // If userVolume = null → volume = 50 const name = userName ?? 'Guest'; // If userName = '' → name = '' (CORRECT!)
🎯 Real-World Examples
// API response handling
const pageSize = response.pageSize ?? 20;
const sortOrder = response.sortOrder ?? 'desc';
const filters = response.filters ?? {};
// Form inputs (0 is valid age)
const age = input.value ?? 0;
// Configuration
const config = {
retryCount: userConfig.retryCount ?? 3,
timeout: userConfig.timeout ?? 5000,
enableCache: userConfig.enableCache ?? true
};
// With optional chaining
const city = user?.address?.city ?? 'Unknown';
// Logical assignment
options.timeout ??= 3000; // Only sets if null/undefined
💡 Browser Support
- Chrome 80+ ✅
- Firefox 72+ ✅
- Safari 13.1+ ✅
- Node.js 14+ ✅
- TypeScript 3.7+ ✅
“Volume slider defaulted to 50 when user set to 0. Used ||. Fixed with ??. 0 is valid! ?? saved the day.”
