In JavaScript, the ||
operator (logical OR) evaluates multiple expressions from left to right and returns the first truthy value it encounters. If all expressions are falsy, it returns the last value.
How it Works
- The
||
operator checks the first operand. If it is truthy, it returns that value and stops further evaluation (short-circuiting). - If the first operand is falsy, it moves to the next operand and evaluates it.
- This process continues until a truthy value is found or the last operand is evaluated.
Truthy and Falsy Values in JavaScript
- Truthy: Values that are considered “true” in a boolean context (e.g., non-zero numbers, non-empty strings, objects,
true
). - Falsy: Values that are considered “false” in a boolean context (e.g.,
0
,""
,null
,undefined
,NaN
,false
).
Example Scenarios
- Multiple ORs with Truthy Values:
let result = 0 || false || "Hello" || 42; console.log(result); // Output: "Hello"
0
is falsy, so it moves tofalse
.false
is falsy, so it moves to"Hello"
."Hello"
is truthy, so it stops and returns"Hello"
.
- All Falsy Values:
let result = 0 || false || null || undefined; console.log(result); // Output: undefined
- Since all values are falsy, it evaluates every operand and returns the last one (
undefined
).
- Since all values are falsy, it evaluates every operand and returns the last one (
- Short-Circuiting:
let result = "JavaScript" || console.log("Not executed"); console.log(result); // Output: "JavaScript"
- The first operand
"JavaScript"
is truthy, so the second operand (console.log()
) is never executed.
- The first operand
- Combining with Default Values:
let username = null; let defaultName = "Guest"; let displayName = username || defaultName; console.log(displayName); // Output: "Guest"
username
isnull
(falsy), sodefaultName
("Guest"
) is used.
Key Notes
- The
||
operator does not return a boolean value unless used in a strict comparison.let result = "Hi" || false; console.log(result); // Output: "Hi" (truthy value, not `true`)
- Order of Evaluation: Operands are evaluated from left to right. This allows
||
to be used for short-circuiting. - Using Multiple ORs in Practice:
- Commonly used to provide default values:
let config = userConfig || defaultConfig;
- Often seen in form validations or fallback mechanisms.
- Commonly used to provide default values:
Summary
When multiple ||
operators are used, JavaScript evaluates each operand in order until it finds the first truthy value. If no truthy value exists, it returns the last operand. This behavior is often leveraged for setting defaults, implementing fallbacks, or controlling program flow with short-circuiting.