Fallback values with ||
Choose a fallback when a value may be falsy.
JS Puzzles · Const
Short-circuit evaluation makes JavaScript stop evaluating a logical expression as soon as its result is determined. The || operator stops at a truthy value, while && stops at a falsy value, and each returns the operand where it stopped.
JavaScript evaluates logical operators from left to right. With ||, evaluation stops at the first truthy value; with &&, it stops at the first falsy value. The operator returns the operand where evaluation stopped, so the result does not have to be a Boolean.
left || right
left && rightThe operand at which evaluation stops; with || this is the first truthy value or the last operand, and with && it is the first falsy value or the last operand.
const supplied = "";
const name = supplied || "Guest";
const enabled = true;
enabled && console.log("Feature is enabled");
let calls = 0;
const result = false && (++calls);
console.log(name, result, calls);The right side of each logical expression runs only when the left side cannot determine the result.
Choose a fallback when a value may be falsy.
Run an action only when a condition is truthy.
Avoid evaluating unnecessary expressions or side effects.
The operands are evaluated from left to right. For ||, JavaScript returns immediately when it finds a truthy operand; for &&, it returns immediately when it finds a falsy operand.
Follow-up: What does 0 || 42 return? It returns 42, because 0 is falsy and evaluation continues to the right operand.
Logical operators return one of their operands rather than converting the result to true or false. Thus, "hello" || "fallback" returns "hello", while "" || "fallback" returns "fallback".
Follow-up: How can a Boolean result be forced? Apply Boolean conversion, such as Boolean(value), or use !!value.
The right operand is skipped when the left operand already determines the result. This makes expressions such as condition && action() useful for conditional execution, because action() runs only when condition is truthy.
Follow-up: What happens with a || b && c? && has higher precedence, so it is grouped as a || (b && c); parentheses can make that grouping explicit.
Logical AND (&&)Logical OR (||)Logical NOT (!)Operator precedence