How to use nullish coalescing in JavaScript
The nullish coalescing operator provides a precise way to handle null and undefined values without affecting other falsy values like empty strings or zero.
As the creator of CoreUI, a widely used open-source UI library, I’ve used nullish coalescing extensively in JavaScript applications for safer default value assignment.
From my 25 years of experience in web development, the nullish coalescing operator (??) is more reliable than logical OR (||) for default values because it only triggers for null and undefined.
This operator prevents unexpected behavior with legitimate falsy values.
Use the nullish coalescing operator (??) to provide default values only when the left side is null or undefined.
const userSettings = {
theme: null,
notifications: false,
timeout: 0,
username: undefined
}
// Nullish coalescing - only null/undefined trigger default
const theme = userSettings.theme ?? 'light' // 'light'
const notifications = userSettings.notifications ?? true // false (not triggered)
const timeout = userSettings.timeout ?? 30 // 0 (not triggered)
const username = userSettings.username ?? 'guest' // 'guest'
// Compare with logical OR (problematic)
const timeoutOR = userSettings.timeout || 30 // 30 (incorrect!)
const notificationsOR = userSettings.notifications || true // true (incorrect!)
// Chaining nullish coalescing
const config = userConfig ?? defaultConfig ?? {}
// With optional chaining
const apiUrl = settings?.api?.url ?? 'https://api.example.com'
The nullish coalescing operator (??) only returns the right operand when the left operand is strictly null or undefined. Unlike the logical OR operator (||), it doesn’t treat other falsy values like 0, false, or '' as triggers for the default value. This makes it perfect for configuration objects where these falsy values are legitimate settings. You can chain multiple nullish coalescing operators and combine them with optional chaining for safe property access.
This is the same precise default value handling we use in CoreUI components to respect user configurations while providing safe fallbacks. Use nullish coalescing instead of logical OR when you need to distinguish between intentional falsy values and missing data.



