Nullish Coalescing Operator
Nullish Coalescing Operator (??)
Section titled “Nullish Coalescing Operator (??)”Introduction
Section titled “Introduction”The nullish coalescing operator ?? returns the right-hand operand only when the left-hand operand is null or undefined. Unlike ||, it doesn’t treat 0, '', or false as falsy.
Why Do We Need This?
Section titled “Why Do We Need This?”The || operator treats 0, '', and false as falsy and replaces them with the default. But sometimes these are valid values — ?? solves this problem.
const count = 0;count || 10; // 10 — wrong! 0 is validcount ?? 10; // 0 — correctVisual Explanation
Section titled “Visual Explanation”flowchart TD Left["Left operand"] Check{"Is left null or undefined?"} Yes["Return right operand"] No["Return left operand"]
Left --> Check Check -->|Yes| Yes Check -->|No| NoExamples
Section titled “Examples”null ?? 'default'; // 'default'undefined ?? 'default'; // 'default'0 ?? 'default'; // 0 — preserved!'' ?? 'default'; // '' — preserved!false ?? 'default'; // false — preserved!Cannot Chain with && or ||
Section titled “Cannot Chain with && or ||”null || undefined ?? 'default'; // SyntaxError!// Use parentheses:(null || undefined) ?? 'default'; // 'default'Summary
Section titled “Summary”??checks fornull/undefinedonly- Use instead of
||when0,'',falseare valid values - Cannot mix with
&&or||without parentheses