JavaScript Nullish Coalescing Operator Fix
In this tutorial, you'll learn about JavaScript Nullish Coalescing Operator Fix. We cover key concepts, practical examples, and best practices.
The Problem
The nullish coalescing operator (??) returns the right-hand side only when the left-hand side is null or undefined. Developers often confuse it with the logical OR (||) which treats all falsy values (0, '', false, NaN) the same way.
Quick Fix
Step 1: Use ?? to preserve falsy values
// Wrong — || treats 0 as falsy
const quantity = 0 || 10;
console.log(quantity); // 10 (unexpected — should be 0)
// Right — ?? only replaces null/undefined
const quantity = 0 ?? 10;
console.log(quantity); // 0
Step 2: Handle empty string correctly
const input = '';
// Wrong — || replaces empty string
const name = input || 'Anonymous';
console.log(name); // Anonymous (unexpected)
// Right — ?? preserves empty string
const name = input ?? 'Anonymous';
console.log(name); // (empty string preserved)
Step 3: Chain multiple defaults
const user = {
settings: null
};
// Wrong — optional chaining with || loses falsy values
const theme = user.settings?.theme || 'dark';
// Right — optional chaining with ?? preserves falsy values
const theme = user.settings?.theme ?? 'dark';
console.log(theme); // dark
Step 4: ?? cannot be combined with && or || without parentheses
// Wrong — SyntaxError
const value = a && b ?? c;
// Right — use parentheses
const value = (a && b) ?? c;
const value2 = a && (b ?? c);
Step 5: Use ??= for default assignment
let count = null;
// Wrong — assignments with ||=
count ||= 10; // Sets to 10 even if count is 0
// Right — use ??= for nullish assignment
count ??= 0; // Sets to 0 only if count is null/undefined
console.log(count); // 0
Prevention
- Use
??when you want to preserve falsy values like0,'',false - Use
||when you want to replace any falsy value with a default - Always wrap
??in parentheses when combining with&&or|| - Use
??=for nullish assignment shorthand - Understand the difference:
??checks nullish,||checks falsy
Common Mistakes with nullish coalescing
- Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
These mistakes appear frequently in real-world JS code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro