JavaScript Interview Question #94

What is the nullish coalescing operator (??)?

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

Quick Interview Answer

The nullish coalescing operator returns its right-hand operand only when the left-hand operand is null or undefined. Values such as 0, false, and an empty string are preserved.

Detailed Explanation

The nullish coalescing operator returns its right-hand operand only when the left-hand operand is null or undefined. Values such as 0, false, and an empty string are preserved.

This differs from using || for defaults because || treats all falsy values as a reason to use the fallback.

Code Example

const pageSize = 0;

console.log(pageSize || 20); // 20
console.log(pageSize ?? 20); // 0

const title = null;
console.log(title ?? "Untitled"); // Untitled