JavaScript Nullish Coalescing Operator Explained

This article provides a comprehensive overview of the JavaScript nullish coalescing operator (??). You will learn what the operator does, the syntax required to use it, how it critically differs from the logical OR operator (||), and how to apply it effectively in real-world programming scenarios to handle default values without introducing bugs.

What is the Nullish Coalescing Operator?

The nullish coalescing operator (??) is a logical operator introduced in ECMAScript 2020 (ES11). It accepts two operands and returns the right-hand operand only when the left-hand operand evaluates to null or undefined. If the left-hand operand is anything other than null or undefined, it returns the left-hand value.

Syntax

const result = leftOperand ?? rightOperand;

If leftOperand is neither null nor undefined, result is assigned the value of leftOperand. Otherwise, result receives the value of rightOperand.

Nullish Coalescing (??) vs. Logical OR (||)

Developers historically used the logical OR operator (||) to assign default fallback values. However, || returns the fallback value for any falsy value, which includes false, 0, "" (empty string), NaN, null, and undefined.

In contrast, the nullish coalescing operator (??) only triggers on nullish values (null and undefined), preserving valid falsy values like 0, false, and "".

Comparison Example

// Using Logical OR (||)
const count = 0;
const finalCount = count || 10;
console.log(finalCount); // Output: 10 (0 is falsy, so it fell back)

// Using Nullish Coalescing (??)
const correctCount = count ?? 10;
console.log(correctCount); // Output: 0 (0 is defined, so it is kept)
// Empty string handling
const userBio = "";
const displayBio = userBio ?? "No bio provided.";
console.log(displayBio); // Output: "" (empty string is preserved)

Short-Circuit Evaluation

The nullish coalescing operator uses short-circuit evaluation. If the left-hand operand is neither null nor undefined, the right-hand operand is not evaluated at all.

function getDefault() {
  console.log("Fallback function executed");
  return "Default Value";
}

const activeValue = "Hello" ?? getDefault();
// Output: "Hello" (getDefault is never called)

Syntax Restrictions with AND and OR

For safety and clarity, JavaScript forbids directly chaining the nullish coalescing operator with the logical AND (&&) or logical OR (||) operators without explicit parentheses.

// Syntax Error
// const value = null || undefined ?? "default";

// Correct Usage
const value = (null || undefined) ?? "default";

Summary

The nullish coalescing operator (??) is the standard way to assign default values in JavaScript when handling variables that might be null or undefined, avoiding unintended fallbacks for valid values like 0, false, or empty strings.