Problem Statement
What does the nullish coalescing operator (??) do?
Explanation
The nullish coalescing operator returns the right operand when the left operand is null or undefined, and returns the left operand otherwise.
Unlike the OR operator which checks for any falsy value, nullish coalescing only checks for null and undefined.
This is useful when zero or empty string are valid values you want to keep.
It was introduced in ES2020 to provide a more precise way to set default values.
Code Solution
SolutionRead Only
// Nullish coalescing - only null/undefined
console.log(null ?? 'default'); // 'default'
console.log(undefined ?? 'default'); // 'default'
console.log(0 ?? 'default'); // 0 (keeps 0)
console.log('' ?? 'default'); // '' (keeps empty string)
console.log(false ?? 'default'); // false (keeps false)
// Compare with OR operator
console.log(0 || 'default'); // 'default' (treats 0 as falsy)
console.log('' || 'default'); // 'default' (treats '' as falsy)
// Practical use
function setPort(port) {
return port ?? 3000; // Keeps 0 as valid port
}
console.log(setPort(8080)); // 8080
console.log(setPort(0)); // 0 (not 3000!)
console.log(setPort(null)); // 3000
// User settings
let volume = settings.volume ?? 50; // 0 is valid volume