*
Previous Optional chaining JavaScript Modules Next

πŸ€” Nullish Coalescing Operator (??) in JavaScript

The nullish coalescing operator (??) is a logical operator in JavaScript that returns its right-hand side operand when its left-hand side operand is null or undefined. It provides a more specific way to handle default values compared to the logical OR operator (||).

πŸ” How it works

The ?? operator checks if the value on its left is "nullish," which includes only null and undefined. If it is, the operator returns the value on its right. Otherwise, it returns the value on its left. This behavior is distinct from the logical OR (||) operator, which returns the right-hand operand for any "falsy" value, including 0, an empty string (""), false, and NaN.

πŸ“˜ What is It?

The ?? operator returns the right-hand operand when the left-hand operand is null or undefined. Otherwise, it returns the left-hand operand. It’s useful for providing default values without mistakenly overriding valid falsy values like 0, false, or "".

🧾 Syntax

//javascript
const result = leftOperand ?? rightOperand;

  

This is equivalent to:

//javascript
const result = (leftOperand !== null && leftOperand !== undefined) ? leftOperand : rightOperand;

  

πŸ§ͺ Syntax and Examples

// Basic usage
const name = null ?? "Guest";
console.log(name); // "Guest"

const age = undefined ?? 18;
console.log(age); // 18

const score = 0 ?? 100;
console.log(score); // 0 (not nullish, so 0 is returned)

const isActive = false ?? true;
console.log(isActive); // false (not nullish, so false is returned)

πŸ’‘ Example

//javascript
const count = 0;
const text = "";
const userSettings = { volume: 0, theme: null };

// Using logical OR (||)
const qty = count || 42;
const message = text || "hello";
console.log(qty); // Output: 42 (Incorrect, as 0 is a valid count)
console.log(message); // Output: "hello" (Incorrect, as an empty string may be a valid value)

// Using nullish coalescing (??)
const qtyWithNullish = userSettings.volume ?? 42;
const messageWithNullish = text ?? "hello";
console.log(qtyWithNullish); // Output: 0 (Correct, preserves the valid falsy value)
console.log(messageWithNullish); // Output: "" (Correct, preserves the valid falsy value)

const theme = userSettings.theme ?? "light";
console.log(theme); // Output: "light" (Provides a fallback for null)

  

πŸ” Comparison with Logical OR (||)

The || operator returns the right-hand operand if the left-hand operand is falsy (e.g., 0, false, "", null, undefined). In contrast, ?? only checks for null or undefined.

const value1 = 0 || 42;   // 42
const value2 = 0 ?? 42;   // 0

πŸ“Š Key differences between ?? and ||

Feature Nullish Coalescing (??) Logical OR (||)
Fallback condition Triggers only if the left operand is null or undefined. Triggers if the left operand is any falsy value (null, undefined, 0, "", false, NaN).
Preserves falsy values Preserves valid falsy values like 0 and "". Does not preserve falsy values; replaces them with the fallback.
Best for Providing default values when you need to specifically check for truly "missing" data, but want to keep other falsy values. Providing a fallback for any value that should be treated as "empty," including 0 or "".

βœ… Advantages

  • πŸ›‘ Preventing unexpected behavior: It solves the common pitfall of the || operator, where values like 0 or "" are unintentionally replaced by a default value.
  • 🎯 Clarity and intent: It clearly communicates that you are only providing a fallback for values that are genuinely nullish.
  • πŸ”— Integration with optional chaining (?.): The two operators work together seamlessly. You can safely access a nested property using optional chaining, and then use nullish coalescing to provide a fallback value if the property was null or undefined.
  • ✍️ Conciseness: It offers a clean, one-line syntax for a common check that would otherwise require a verbose conditional statement.
  • Provides safer default values
  • Preserves valid falsy values like 0 or false
  • Improves clarity over || in many cases

⚠️ Precautions

  • 🚫 Don't combine without parentheses: You cannot directly combine the ?? operator with && or || in the same expression without using parentheses to specify the order of operations.
  • 🌐 Check for browser support: While widely supported, it was introduced in ES2020. Ensure compatibility with older browsers if necessary.

🎯 Use cases

Providing default values for function arguments

//javascript
function greet(name, age) {
  const userName = name ?? "Guest";
  const userAge = age ?? "unknown";
  console.log(`Hello, ${userName}! Your age is ${userAge}.`);
}

greet(null, 30);      // Output: "Hello, Guest! Your age is 30."
greet("Alice", null); // Output: "Hello, Alice! Your age is unknown."
greet("Bob", 0);      // Output: "Hello, Bob! Your age is 0."

  

Accessing potentially missing object properties

//javascript
const user = {
  id: 123,
  name: "Jane",
  address: null
};

const userCity = user.address?.city ?? "Not specified";
console.log(userCity); // Output: "Not specified"

  

Handling configurations where 0 is a valid setting

//javascript
const config = { maxConnections: 0, timeout: null };

const maxConnections = config.maxConnections ?? 10;
const timeout = config.timeout ?? 5000;

console.log(maxConnections); // Output: 0
console.log(timeout); // Output: 5000
  

❌ Disadvantages

  • Not supported in older browsers without transpilation
  • Can be misused if the distinction between falsy and nullish isn’t clear

πŸ“Œ When to Use

  • When you want to provide a default only for null or undefined
  • When working with optional data (e.g., API responses)
  • When preserving falsy values like 0 or false is important

🚫 When Not to Use

  • When you want to override all falsy values (use || instead)
  • In environments that don’t support ES2020

🧠 Best Practices

  • Use ?? for nullish checks, not general falsy checks
  • Combine with optional chaining for safe access and defaults:
    const userName = user?.profile?.name ?? "Guest";
  • Avoid chaining too deeply without understanding the data structure

πŸ”— References

Back to Index
Previous Optional chaining JavaScript Modules Next
*
*