Sub topic 6
How && Picks the First Falsy Operand
This chapter assumes you know the falsy values (false, 0, -0, 0n, "", null, undefined, NaN), that every other value is truthy, and how || returns one of its operands. You should also be comfortable reading console.log output and writing small functions.
The && operator looks like a plain "and" from logic, but it does not produce true or false on its own. It returns one of the values you gave it. Once you know which one, many common idioms make sense, and so do the bugs that come with them.
The Rule in One Sentence
a && b evaluates a. If a is falsy, the result is a itself. Otherwise, the result is b, whatever b is.
The language specification describes the same steps:
- Evaluate the left operand and get its value.
- Convert that value to a boolean (internally, with the
ToBooleanoperation) only to decide what to do next. - If the boolean is
false, return the original left value, not the boolean. - Otherwise, evaluate the right operand and return its value unchanged.
Step 3 is the part people miss. The conversion to a boolean is used to make the decision and then thrown away. The value you get back is never converted. Also note that the right operand is never tested at all. && returns it as it is.
Seeing It in Action
Run this in Node.js or a browser console. The comments show values in JavaScript notation, so the console prints b where the comment says "b".
console.log("a" && "b"); // "b" left is truthy, so the right side is returned
console.log(0 && "b"); // 0 left is falsy, so it is returned
console.log("" && "b"); // "" empty string is falsy
console.log(null && "b"); // null
console.log(NaN && "b"); // NaN
console.log("a" && 0); // 0 left is truthy, right is returned even though it is falsy
console.log([] && {}); // {} both truthy, the right side is returned
console.log(true && false); // falseNone of these results was converted to a boolean. 0 && "b" gives you the number 0, and [] && {} gives you the object.
| Expression | Is the left operand truthy? | Result | Type of result |
|---|---|---|---|
| `"a" && "b"` | yes | `"b"` | string |
| `0 && "b"` | no | `0` | number |
| `null && "b"` | no | `null` | object (null) |
| `"a" && 0` | yes | `0` | number |
| `[] && {}` | yes | `{}` | object |
| `undefined && f()` | no | `undefined` | undefined |
Chains: First Falsy, or the Last Operand
&& is left-associative, so a && b && c is read as (a && b) && c. Combined with the rule above, a chain returns the first falsy operand it meets. If every operand is truthy, it returns the last operand.
console.log(1 && "x" && [] && 42); // 42 all truthy, last one wins
console.log(1 && "" && [] && 42); // "" first falsy operand
console.log(1 && "x" && null && 0); // null first falsy, the later 0 is never reached
console.log("only"); // a single value: no && involvedThis mirrors ||, which returns the first truthy operand or the last operand. One way to remember both: each operator stops at the first value that settles the answer. For "and", one falsy value settles it. For "or", one truthy value settles it.
Once && stops, it does not evaluate the operands to its right at all. The next chapter covers that behavior, short-circuit evaluation, and what it means for function calls and side effects.
When the Returned Operand Does Not Matter
Inside a boolean context such as if, while, the ternary condition, or !, JavaScript converts the result to a boolean anyway. There the operand-returning behavior has no visible effect:
const name = "Ada";
const age = 0;
if (name && age) {
console.log("both present");
} else {
console.log("at least one is falsy"); // runs, because age is 0
}The && expression produces 0, and if treats 0 as false. You get the same result you would get if && returned a boolean.
When the Returned Operand Does Matter
The difference shows up when you store, return, print, or compare the result instead of only testing it.
Property access guards
Before optional chaining existed, && was the standard way to read nested properties without throwing a TypeError:
function getCity(user) {
return user && user.address && user.address.city;
}
console.log(getCity(null)); // null
console.log(getCity({})); // undefined
console.log(getCity({ address: { city: "Oslo" } })); // "Oslo"
console.log(getCity({ address: { city: "" } })); // ""The guard works, but the "missing" result changes with the input: null, undefined, or "". Code that later checks result === undefined will miss the null case. A truthy but unusable value, such as user = 5, also gets through: 5 && (5).address gives undefined without an error, which may hide a bug. A later chapter shows how ?. handles this more precisely.
Values that are supposed to be booleans
A function whose name promises a boolean can quietly return something else:
function isAdult(user) {
return user && user.age >= 18;
}
console.log(isAdult({ age: 30 })); // true
console.log(isAdult({ age: 10 })); // false
console.log(isAdult(null)); // null, not false
console.log(isAdult(undefined)); // undefined, not falseThat matters if the result goes into JSON, into a strict comparison like isAdult(u) === false, or into a typed API. Make the left operand a real boolean so that every path returns one:
function isAdult(user) {
return Boolean(user) && user.age >= 18;
}
console.log(isAdult(null)); // false
console.log(isAdult({ age: 30 })); // trueBecause Boolean(user) is always true or false, and user.age >= 18 is always a boolean, the whole expression is now always a boolean. !!user && user.age >= 18 does the same thing. Wrapping the whole expression, as in Boolean(user && user.age >= 18), also works.
Numbers on the left
A falsy number on the left comes back as a number. This is the most common && bug in user interface code:
const unread = 0;
const message = unread && `You have ${unread} new messages`;
console.log(message); // 0
console.log(typeof message); // "number"
console.log(`Status: ${message}`); // "Status: 0"If the template or framework prints whatever it receives, the user sees a stray 0. NaN behaves the same way and prints as NaN. The guard-patterns chapter covers fixes in more detail. The short version is to make the condition an explicit comparison, such as unread > 0 && ....
Common Errors
| Mistake | What actually happens | Fix | Column | Column | Column | Column | Column | Column |
|---|---|---|---|---|---|---|---|---|
| Assuming `a && b` is `true` or `false` | It returns `a` or `b` unchanged | Wrap with `Boolean(...)` when you need a boolean | ||||||
| Expecting `&&` to test the right operand | The right operand is returned without being tested | Test it separately if its truthiness matters | ||||||
| Using a count or index as the left operand | `0` is returned and may be displayed | Compare explicitly: `count > 0 && ...` | ||||||
| Treating every falsy result as `undefined` | You may get `null`, `""`, `0`, `NaN`, or `false` | Check with a falsy test, or normalize the result | ||||||
| Mixing `&&` and `\ | \ | ` without parentheses | `&&` binds tighter: `a \ | \ | b && c` is `a \ | \ | (b && c)` | Add parentheses to show intent |
The last row previews a later chapter on precedence. For now, remember that && groups before ||, the same way multiplication groups before addition:
console.log(true || false && false); // true read as true || (false && false)
console.log((true || false) && false); // falseExercises
Exercise
What does each line print, and why? (1) console.log("0" && "zero"); (2) console.log(-0 && "x"); (3) console.log([] && "" && {}); (4) console.log({} && [] && 7);
Show answer
(1) "zero": the string "0" is non-empty and therefore truthy, so the right operand is returned. (2) -0 (Node prints -0): -0 is falsy and is returned unchanged. (3) "": [] is truthy, "" is the first falsy operand, and evaluation stops there. (4) 7: every operand is truthy, so the last one is returned.
Exercise
The function hasItems(cart) is written as return cart && cart.items.length; Name every kind of value it can return, and rewrite it so it always returns a boolean.
Show answer
It can return any falsy value passed as cart (null, undefined, 0, "", false, NaN, 0n), or a number from cart.items.length (including 0). It also throws a TypeError if cart is truthy but has no items property. A boolean version: return Boolean(cart) && Array.isArray(cart.items) && cart.items.length > 0; Each operand is a boolean, so the result is always true or false.
Exercise
Without running it, give the value of x in: const x = null || 0 && "a" || "b";
Show answer
"b". && binds tighter, so this is null || (0 && "a") || "b". The inner part is 0 && "a", which is 0. Then null || 0 || "b" returns the first truthy operand, "b".