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)
|| (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)
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
By understanding these differences, you can make better decisions on which operator to use based on your needs! 🚀
Top comments (0)