Skip to content

Nullish Coalescing Operator

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.

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 valid
count ?? 10; // 0 — correct
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| No
null ?? 'default'; // 'default'
undefined ?? 'default'; // 'default'
0 ?? 'default'; // 0 — preserved!
'' ?? 'default'; // '' — preserved!
false ?? 'default'; // false — preserved!
null || undefined ?? 'default'; // SyntaxError!
// Use parentheses:
(null || undefined) ?? 'default'; // 'default'
  • ?? checks for null/undefined only
  • Use instead of || when 0, '', false are valid values
  • Cannot mix with && or || without parentheses