Sub topic 5
How || Picks the First Truthy Operand
This chapter assumes you can declare variables with let and const, know the primitive types and objects, write if statements and functions, and read console.log output. It also builds on the earlier chapters: you should know the eight falsy values and that everything else is truthy.
Many developers first meet || as "logical OR" and expect it to produce true or false. In JavaScript, that expectation is wrong. The || operator returns one of its operands, unchanged. This chapter explains the exact rule, how it extends to chains of operands, and the mistakes it causes in real code.
The Rule in One Sentence
a || b evaluates a. If a is truthy, the result is a. Otherwise, the result is b.
No boolean conversion happens to the returned value. JavaScript converts a to a boolean only to make the decision, then throws that boolean away and hands back the original value.
console.log("a" || "fallback"); // "a"
console.log("" || "fallback"); // "fallback"
console.log(null || 0); // 0
console.log(42 || false); // 42
console.log(false || false); // falseLook at null || 0. Both operands are falsy, so || returns the right-hand one, 0. It does not return false. The result is exactly the second operand, whatever it happens to be.
How the Engine Evaluates ||
The language specification describes || in a few steps:
- Evaluate the left operand and keep its value,
lval. - Convert
lvalto a boolean using the same truthiness rules as anifcondition. - If that boolean is
true, returnlval. - Otherwise, evaluate the right operand and return its value.
Step 4 never checks whether b is truthy. Once the left side is falsy, the right side becomes the answer no matter what it is. Step 3 also means the right operand is not evaluated at all when the left side is truthy. That behavior is called short-circuit evaluation, and a later chapter covers it on its own, including its effect on function calls and side effects.
A Truth Table with Real Values
Here is the operator's behavior across a mix of operand types. The "Result" column shows the actual value produced, not a boolean.
| Left operand | Right operand | Left is truthy? | Result |
|---|---|---|---|
| `"hi"` | `"bye"` | yes | `"hi"` |
| `0` | `"bye"` | no | `"bye"` |
| `[]` | `"bye"` | yes | `[]` |
| `""` | `0` | no | `0` |
| `NaN` | `undefined` | no | `undefined` |
| `"0"` | `1` | yes | `"0"` |
| `{}` | `null` | yes | `{}` |
The rows with [] and "0" are the ones that catch people out. An empty array and the string "0" are truthy, so || stops there and returns them.
Objects Come Back by Reference
When || returns an object, it returns that same object, not a copy. You can confirm this with strict equality:
const config = { debug: true };
const chosen = config || { debug: false };
console.log(chosen === config); // true
chosen.debug = false;
console.log(config.debug); // falseChanging chosen changes config because both names point at one object. Keep this in mind when you use || to pick between a shared object and a fresh one.
Chains: First Truthy or Last Operand
|| is left-associative, so a || b || c is parsed as (a || b) || c. Apply the rule twice and you get a simple summary:
- The result is the first truthy operand, reading left to right.
- If no operand is truthy, the result is the last operand.
console.log(0 || "x" || "y"); // "x"
console.log(0 || "" || null); // null
console.log(undefined || NaN || 0); // 0
console.log(false || [] || "z"); // []In 0 || "" || null, every operand is falsy, so the chain returns the last one, null. In false || [] || "z", the empty array is the first truthy value, so "z" is never reached.
This makes || chains useful for picking the first value that exists from a list of candidates:
function displayName(user) {
return user.nickname || user.fullName || user.email || "Guest";
}
console.log(displayName({ nickname: "", fullName: "Ada Lovelace" })); // "Ada Lovelace"
console.log(displayName({ email: "[email protected]" })); // "[email protected]"
console.log(displayName({})); // "Guest"The final "Guest" always ends the chain, because if everything before it is falsy, the last operand is returned. Putting a guaranteed value at the end means the function never returns undefined.
Why if (a || b) Still Works
If || does not return a boolean, why does if (a || b) behave as expected? Because the if statement performs its own boolean conversion on whatever value it receives.
const input = "";
const backup = "saved";
if (input || backup) {
console.log("have a value"); // logs, because "saved" is truthy
}
const result = input || backup;
console.log(result); // "saved"In a boolean context, getting back a truthy operand and getting back true lead to the same branch. The difference only shows up when you store, return, compare or print the result.
Common Errors
Expecting a boolean in a variable
const user = { name: "Sam", email: "" };
const hasContact = user.email || user.name;
console.log(hasContact); // "Sam"
console.log(typeof hasContact); // "string"
console.log(JSON.stringify({ hasContact })); // {"hasContact":"Sam"}A field named hasContact that holds "Sam" will confuse anyone reading the data, and it fails a check like hasContact === true. If you need a real boolean, convert explicitly:
const user = { name: "Sam", email: "" };
const hasContact = Boolean(user.email || user.name);
console.log(hasContact); // trueComparing the result with true
const a = 5;
const b = 0;
console.log((a || b) === true); // false, because the result is 5
console.log(Boolean(a || b)); // trueStrict comparison with true only succeeds when the chosen operand is literally true. Test the value in a boolean context, or convert it first.
Writing x === "a" || "b"
This bug shows up often in real code:
const role = "viewer";
if (role === "admin" || "editor") {
console.log("access granted"); // logs, which is wrong
}=== has higher precedence than ||, so the condition is (role === "admin") || "editor". The left side is false, so the result is "editor", a non-empty string, which is truthy. The condition passes for every role. Repeat the comparison on each side:
const role = "viewer";
if (role === "admin" || role === "editor") {
console.log("access granted");
} else {
console.log("access denied"); // logs
}
// Or, for longer lists:
console.log(["admin", "editor"].includes(role)); // falseForgetting that the right operand is returned unchecked
const fromCache = null;
const fromServer = undefined;
const data = fromCache || fromServer;
console.log(data); // undefined|| does not guarantee a truthy result. If every operand can be falsy, the result can be falsy too. End the chain with a value you know is safe if the code after it depends on having one.
How || Differs from Other Languages
| Language | `a or b` returns | Example result of `0 or "x"` | Column | Column |
|---|---|---|---|---|
| JavaScript (`\ | \ | `) | One of the operands | `"x"` |
| Python (`or`) | One of the operands | `"x"` | ||
| Java, C# (`\ | \ | `) | A boolean, and both operands must be boolean | compile error |
| C (`\ | \ | `) | The integer `0` or `1` | `1` |
If you come from Java or C#, the operand-returning behavior is the main thing to unlearn. Python developers will find it familiar, though Python's falsy set differs: an empty list is falsy in Python and truthy in JavaScript.
Exercise
What does each line print? (a) console.log(0 || null || "end"); (b) console.log("" || [] || 7); (c) console.log(NaN || undefined); (d) console.log(typeof (0 || ""));
Show answer
(a) "end", because 0 and null are falsy and "end" is the first truthy operand. (b) [], because the empty array is truthy and comes before 7. (c) undefined, because both operands are falsy, so the last operand is returned. (d) "string", because both operands are falsy, so the result is the last operand "", whose type is string.
Exercise
A teammate writes const isReady = status === "done" || "complete"; and later checks if (isReady === true). Explain what goes wrong when status is "pending", and rewrite the line so isReady is always a boolean that is true for either status.
Show answer
With status "pending", the comparison gives false, so || returns its right operand "complete". isReady becomes the string "complete", so isReady === true is false. Any plain truthiness check on isReady would always pass, whatever the status. A correct version is const isReady = status === "done" || status === "complete";. Both operands are now booleans, so the result is always true or false.
Exercise
Write a function firstTruthy(...values) that behaves like chaining || across all its arguments: it returns the first truthy argument, or the last argument if none are truthy (and undefined if called with no arguments). Do not use the || operator inside it.
Show answer
function firstTruthy(...values) { for (const v of values) { if (v) return v; } return values[values.length - 1]; } For example, firstTruthy(0, "", "x", "y") returns "x", firstTruthy(0, null) returns null, and firstTruthy() returns undefined, because values[-1] is undefined.