JavaScript Operators: Understanding ?? (Nullish Coalescing) vs || (OR)

JavaScript provides multiple operators for handling fallback values, and two of the most powerful are the Nullish Coalescing Operator (??) and the Logical OR Operator (||). Both are used to assign default values when a variable is null or undefined, but they behave differently in certain situations.

Let’s dive into the differences and when you should use each.

1. The Logical OR Operator (||)

The || operator returns the first truthy value or the last value if none are truthy. This means it checks for values that are falsy, which include:

  • false
  • 0
  • "" (empty string)
  • null
  • undefined
  • NaN
let value = 0;
let result = value || 100;
console.log(result);  // Output: 100

In this example, value is 0 (falsy), so 100 is returned as the default.

2. The Nullish Coalescing Operator (??)

The ?? operator is similar to ||, but it only checks for null or undefined, ignoring other falsy values like 0, false, or "".

let value = 0;
let result = value ?? 100;
console.log(result);  // Output: 0

In this case, value is 0, but because it’s not null or undefined, ?? returns 0 instead of the fallback 100.

Key Differences Between || and ??

  • || checks for any falsy value, such as 0, false, or an empty string.
  • ?? only checks for null or undefined.
Operator Returns fallback for: Ignores falsy values:
|| 0, false, ""
?? null, undefined false, 0, "", NaN

3. When to Use ||

Use the || operator when you want to provide a default value for all falsy values. This is useful when you want to replace values like 0, false, or empty strings with a more meaningful fallback.

Example:

let userName = "";
let defaultUser = userName || "Guest";
console.log(defaultUser);  // Output: Guest

In this case, the empty string is treated as falsy, and "Guest" is returned.

4. When to Use ??

The ?? operator is best used when you only want to handle cases where the value is null or undefined and leave other falsy values (like 0 or false) intact.

Example:

let score = 0;
let defaultScore = score ?? 10;
console.log(defaultScore);  // Output: 0

Here, score is 0, but ?? doesn’t treat it as falsy, so it returns 0 rather than the fallback value 10.

5. Combining || and ??

You can combine || and ?? to create more flexible conditions depending on your needs:

let userInput = null;
let defaultValue = userInput ?? "Default" || "Fallback";
console.log(defaultValue);  // Output: "Default"

In this example, if userInput is null or undefined, "Default" will be used. If "Default" were falsy, then "Fallback" would be used as the last resort.

Conclusion

  • Use || when you want to handle any falsy value (false, 0, "").
  • Use ?? when you specifically want to handle null and undefined while preserving other falsy values.

Understanding the key differences between these two operators will help you write more predictable and maintainable JavaScript code.