Apply safe defaults
A setting may be absent but zero, false, or an empty string can be meaningful.
JS Puzzles · Const
The ?? operator returns its left value unless it is null or undefined, in which case it returns the right value. It is commonly used for defaults while preserving meaningful falsy values such as 0, false, and ''.
The nullish coalescing operator evaluates its left operand first. It returns that value when it is neither null nor undefined; otherwise it evaluates and returns the right operand. Chaining the operator selects the first non-nullish value, making it useful for defaults without treating values such as 0, false, or an empty string as missing.
leftExpr ?? rightExpr| Name | Type | Description |
|---|---|---|
a | any expression | Expression checked for null or undefined. |
b | any expression | Fallback expression evaluated when the left expression is null or undefined. |
The left operand if it is not null or undefined; otherwise, the right operand.
const configured = 0;
const retries = configured ?? 3;
const timeout = null ?? 5000;
console.log(retries); // 0
console.log(timeout); // 5000The operator preserves valid falsy values such as 0, but substitutes the fallback for null or undefined.
A setting may be absent but zero, false, or an empty string can be meaningful.
Several optional sources can provide the same value.
A fallback expression is expensive or has side effects.
It returns the left operand unless that operand is null or undefined; otherwise it returns the right operand. Unlike ||, it does not replace other falsy values such as 0 or false.
Follow-up: When does the right operand run? It is evaluated only when the left operand is nullish, so the operator short-circuits.
Use ?? when a fallback should apply only to null or undefined. For example, a configured value of 0 should remain 0 rather than being replaced.
Follow-up: How can several possible values be searched? Chain the operator, such as first ?? second ?? fallback, to obtain the first non-nullish value.
The expression a ?? b is valid, but combining ?? directly with && or || is not allowed. Parentheses make the intended grouping explicit, such as (a ?? b) || c.
Follow-up: Why is explicit grouping useful? It prevents precedence misunderstandings when a defaulting expression is embedded in a larger condition.
Logical OR operator ||Logical AND operator &&Conditional operator ?: