Nullish Coalescing Operator (??)
The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.
1. The Problem with || (Logical OR)
Before ??, developers often used the logical OR operator (||) to provide default values.
const count = 0;
const text = "";
const qty = count || 42;
const message = text || "hi!";
console.log(qty); // 42 (0 is falsy)
console.log(message); // "hi!" ("" is falsy)
The issue is that || checks for falsy values. 0, "" (empty string), and false are falsy, so valid values are often overwritten by defaults unintentionally.
2. The Solution: ??
The nullish coalescing operator only checks for nullish values (null or undefined).
const count = 0;
const text = "";
const qty = count ?? 42;
const message = text ?? "hi!";
console.log(qty); // 0
console.log(message); // ""
It correctly preserves 0 and empty strings.
3. When to use which?
- Use
||if you want to treat0,false, or""as invalid values that need a fallback. - Use
??if you only want to handlenullorundefined(missing data).
4. Short-Circuiting
Like || and &&, the right-hand expression is not evaluated if the left-hand side proves the result.
const result = "value" ?? console.log("This won't run");
// result is "value"
5. Chaining with && or ||
For safety, JavaScript forbids combining ?? directly with && or || without parentheses, because the precedence can be confusing.
// SyntaxError
// null || undefined ?? "foo";
// Correct
(null || undefined) ?? "foo"; // "foo"
programming/javascript/vanilla/javascript programming/javascript/vanilla/truthy-falsy programming/javascript/vanilla/optional-chaining