The nullish coalescing operator, ??, provides a fallback only when the left-hand value is null or undefined.
const username = null;
const name = username ?? 'Guest';
console.log(name); // Guest
?? vs. ||
|| falls back for every falsy value. ?? preserves valid falsy data such as 0, false, and '':
const count = 0;
console.log(count || 10); // 10
console.log(count ?? 10); // 0
Function Defaults
function getPrice(price, discount) {
discount = discount ?? 0;
return price - price * discount;
}This treats null and undefined as missing while allowing a discount of 0.
Combine with Optional Chaining
const user = { profile: { name: 'Alice' } };
const bio = user.profile?.bio ?? 'Bio not available';Optional chaining safely reads the property and ?? supplies the fallback.
Operator Mixing
JavaScript does not allow ?? to be mixed directly with || or && without grouping:
const value = (input || fallbackA) ?? fallbackB;Use parentheses to make the intended precedence explicit.
Conclusion
Use ?? when only null and undefined should mean “missing.” It is usually safer than || for configuration values, numeric fields, booleans, and strings where falsy values may be meaningful.