DEV Community

Cover image for Understanding the ?? (Nullish Coalescing) Operator vs. || (Logical OR) in JavaScript
Rutuja
Rutuja

Posted on

Understanding the ?? (Nullish Coalescing) Operator vs. || (Logical OR) in JavaScript

In JavaScript, the ?? (nullish coalescing operator) is often used as an alternative to the logical OR (||), but with a key difference. While both operators provide a fallback value when the left-hand side is falsy, ?? only considers null and undefined as "falsy" values, whereas || considers all falsy values (like false, 0, NaN, '', null, undefined).

Key Differences?? (Nullish Coalescing Operator)

let value = null ?? "default"; // "default"
let value2 = undefined ?? "default"; // "default"
let value3 = "" ?? "default"; // "" (because empty string is not null or undefined)
let value4 = 0 ?? "default"; // 0 (because 0 is not null or undefined)
Enter fullscreen mode Exit fullscreen mode

|| (Logical OR Operator)

let value = null || "default"; // "default"
let value2 = undefined || "default"; // "default"
let value3 = "" || "default"; // "default" (because empty string is falsy)
let value4 = 0 || "default"; // "default" (because 0 is falsy)
Enter fullscreen mode Exit fullscreen mode

When to Use ??
Use ?? instead of || when you only want to fallback for null or undefined while keeping other falsy values (like 0, "", false) intact.

Example:

const count = 0;
const result = count ?? 10;  // result is 0, because count is neither null nor undefined
Enter fullscreen mode Exit fullscreen mode

By understanding these differences, you can make better decisions on which operator to use based on your needs! 🚀

Top comments (0)