JavaScript Interview Question #95

What is the difference between || and ?? for default values?

Promises, Async/Await, Fetch & Modern JavaScript Mid-Level Intermediate

Quick Interview Answer

The logical OR operator returns the right operand when the left operand is falsy. Nullish coalescing returns the right operand only when the left operand is null or undefined.

Detailed Explanation

The logical OR operator returns the right operand when the left operand is falsy. Nullish coalescing returns the right operand only when the left operand is null or undefined.

Use ?? when valid values such as 0, false, or an empty string must be retained. Use || when the application intentionally treats every falsy value as absent.

Code Example

const retries = 0;
const enabled = false;

console.log(retries || 3);  // 3
console.log(retries ?? 3);  // 0

console.log(enabled || true); // true
console.log(enabled ?? true); // false