How does the nullish coalescing operator (??) differ from the logical OR operator (||) for providing default values?
Short answer
?? only falls back to its right-hand side when the left-hand side is SPECIFICALLY null or undefined; || falls back for ANY falsy value, including 0, '', NaN, and false — which can cause bugs when a legitimately valid falsy value gets incorrectly overridden by a default.
Advertisement
AModel answer
?? only falls back to its right-hand side when the left-hand side is SPECIFICALLY null or undefined; || falls back for ANY falsy value, including 0, '', NaN, and false — which can cause bugs when a legitimately valid falsy value gets incorrectly overridden by a default.
const count = 0;
console.log(count || 10); // 10 -- WRONG, treats valid 0 as 'missing'
console.log(count ?? 10); // 0 -- correct, 0 is a valid value, not null/undefinedReal-world example
Providing a default page size or quantity value where 0 is a legitimately valid input that shouldn't be overridden.
Likely follow-ups
- Why can't you mix ?? and || directly in the same expression without parentheses?
Related topics