Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

??: a fallback only for null and undefined

The ?? operator selects its right operand only when the left one is null or undefined. It preserves valid zero, false, and empty-string values.

Version: ECMAScript 2020+

Syntax

value ?? fallback

value ?? fallback evaluates the left operand first. If it is neither null nor undefined, that value is the result and the right expression is not evaluated. Otherwise, the right operand is evaluated. This short-circuiting matters when calculating a fallback calls a function.

|| behaves differently: it chooses the right side for every falsy value, including 0, false, "", and NaN. Thus quantity ?? 1 preserves a quantity of zero, while quantity || 1 replaces it.

You cannot directly mix ?? with || or && without parentheses: that is a syntax error. Make the intended grouping explicit, for example (value ?? fallback) || finalValue. ?? does not validate ranges, text formats, or NaN; it only chooses based on null or undefined.

Examples

console.log(0 ?? 1, 0 || 1);
console.log(false ?? true);
console.log(null ?? "fallback");
let calls = 0;
const value = 7 ?? (++calls);
console.log(value, calls);

Result

0 1
false
fallback
7 0

Sources