Fallback defaults
Provide defaults for empty strings, zero-like values, or other falsy configuration values.
JS Puzzles · Const
Logical assignment operators conditionally assign values using ||=, &&=, or ??=. They short-circuit, so the right-hand expression runs only when assignment is needed.
Logical assignment operators combine a logical test with assignment. ||= assigns when the left side is falsy, &&= assigns when it is truthy, and ??= assigns only when it is null or undefined; the right side is skipped when assignment is unnecessary.
left ||= right
left &&= right
left ??= right| Name | Type | Description |
|---|---|---|
left | assignable reference | Left-hand variable, property, or other assignable reference tested by the operator. |
right | expression | Expression evaluated only when the operator's condition allows assignment. |
The assignment expression evaluates to the resulting value of the left-hand reference.
&&=, ||=, and ??=.let displayName = "";
displayName ||= "Guest";
let retries;
retries ??= 3;
let ready = true;
ready &&= false;
console.log(displayName, retries, ready);Each operator conditionally assigns a fallback or replacement value based on the left-hand operand.
Provide defaults for empty strings, zero-like values, or other falsy configuration values.
Initialize a value only when it is null or undefined without replacing valid falsy values.
Update a value only when an existing value passes a truthiness check.
Logical operatorsAssignmentsNullish coalescing operatorShort-circuit evaluation