QA
Beginner LevelJavaScript & TypeScript

What is the nullish coalescing operator (??) vs Logical OR (||)?

❓ Interview Prompt: Compare ?? and || regarding falsy values (0, "", false) versus nullish values (null, undefined).

Both ?? and || provide fallback values, but trigger on different conditions:

Logical OR (||):

Triggers fallback for ANY falsy value: false, 0, "", null, undefined, NaN.

•
Problem: Overwrites valid falsy values like 0 (valid count) or "" (valid empty string).

Nullish Coalescing (??):

Triggers fallback ONLY for nullish values: null and undefined.

•
Preserves 0, false, and "".

Code Implementation Example

javascript
const config = {
  animationSpeed: 0,
  title: '',
  showSidebar: false,
  timeout: null
};

// Logical OR (||) overwrites legitimate 0, '', and false!
console.log(config.animationSpeed || 300); // 300 ❌ (wanted 0)
console.log(config.title || 'Untitled');     // 'Untitled' ❌ (wanted '')
console.log(config.showSidebar || true);    // true ❌ (wanted false)

// Nullish Coalescing (??) preserves valid falsy data!
console.log(config.animationSpeed ?? 300); // 0 ✅
console.log(config.title ?? 'Untitled');     // '' ✅
console.log(config.showSidebar ?? true);    // false ✅
console.log(config.timeout ?? 5000);         // 5000 ✅ (null triggers fallback)
💡Comparing || (overwrites 0/false) with ?? (preserves 0/false).
🎯 Interview Key Takeaway

Use ?? when setting default values for numbers, booleans, or strings where 0, false, or "" are valid.

#Nullish Coalescing#Operators#ES2020#Beginner
Back to all JavaScript & TypeScript Questions→

More JavaScript & TypeScript Interview Questions

Beginner LevelJavaScript & TypeScript

What are the differences between var, let, and const in JavaScript?

Beginner LevelJavaScript & TypeScript

What are the JavaScript data types and the difference between primitives and objects?

Beginner LevelJavaScript & TypeScript

What is the difference between == (loose equality) and === (strict equality)?