Topic 12 of 37
??
Overview
Introduced in ES2020, ?? is a logical operator that returns its right-hand operand when its left-hand operand is null or undefined, and otherwise returns its left-hand operand. It's much safer than || when 0 or '' are valid default values.
Syntax
?? only considers 'null' and 'undefined' as nullish, meaning 0, false, and '' are preserved.
?? vs ||
javascript
const score = 0;
// Bad: || treats 0 as falsy and replaces it with 100
const finalScoreOR = score || 100; // Returns 100
// Good: ?? only looks for null or undefined
const finalScoreNullish = score ?? 100; // Returns 0Common Pitfalls
- You cannot chain ?? with && or || without explicit parentheses (e.g., a ?? b || c throws a SyntaxError).
Interview Tips
- Know exactly which values trigger the fallback for || (all falsy values) versus ?? (only null/undefined).
Real-World Example
Setting default configuration values safely.
example
javascript
function setupGame(config) {
// If user explicitly sets volume to 0, we want to keep it at 0.
const volume = config.volume ?? 50;
const difficulty = config.difficulty ?? 'medium';
}