How to use nullish coalescing in JavaScript
· Category: JavaScript
Short answer
The ?? operator returns the right-hand operand only when the left-hand operand is null or undefined, unlike || which treats all falsy values as missing.
Steps
- Provide a default for nullish values:
javascript const count = 0; const result = count ?? 10; // 0 - Contrast with logical OR:
javascript const resultOr = count || 10; // 10 (wrong for 0) - Chain defaults:
javascript const port = config.port ?? process.env.PORT ?? 3000; - Combine with optional chaining:
javascript const name = user?.name ?? "Guest";
Tips
- Use
??for configuration values where0,false, or""are valid. - Parenthesize when mixing with
&&or||to avoid precedence errors.
Common issues
- Mixing
??with&&or||without parentheses throws a syntax error in some older parsers. - Developers mistakenly use
||for numeric defaults, causing0to be overwritten.