Sub topic 13
&&, ||, and ! as Value Selectors
This chapter assumes you already know which values are truthy and which are falsy, and that you can read basic operator precedence. Here you will see what the logical operators actually return. In JavaScript, && and || do not always return true or false. They return one of their operands, and they may skip evaluating the right side completely. If you understand those two facts, you can predict every logical expression and avoid a common class of default-value bugs.
What Each Operator Returns
! is the only logical operator that always returns a boolean. && and || look at the left operand's truthiness and then return one of the two operands unchanged.
| Expression | If `a` is truthy | If `a` is falsy | Return type | Column | Column |
|---|---|---|---|---|---|
| `a \ | \ | b` | returns `a` (skips `b`) | evaluates and returns `b` | type of the chosen operand |
| `a && b` | evaluates and returns `b` | returns `a` (skips `b`) | type of the chosen operand | ||
| `!a` | `false` | `true` | always boolean |
The mental model is short:
||returns the first truthy operand, or the last operand if none is truthy.&&returns the first falsy operand, or the last operand if none is falsy.
console.log(0 || 'default'); // 'default'
console.log('a' || 'b'); // 'a'
console.log(null || 0 || ''); // '': no truthy operand, so the last one is returned
console.log('' && 'never'); // ''
console.log('a' && 'b'); // 'b'
console.log(1 && 2 && 3); // 3: no falsy operand, so the last one is returned
console.log(1 && 0 && 3); // 0: the first falsy operandThe result of 'a' && 'b' is the string 'b', not true. An if statement converts that string to true anyway, so inside conditions you usually won't notice. The difference shows up when you store or return the result.
Short-Circuit Evaluation
Short-circuit evaluation means the right operand is not evaluated at all when the left operand already decides the result. A skipped right operand produces no side effects: its function calls, assignments, and errors never happen.
function log(x) {
console.log('evaluated', x);
return x;
}
log(0) && log(1); // prints only: evaluated 0
log(1) || log(2); // prints only: evaluated 1
log(1) && log(2); // prints: evaluated 1, then evaluated 2Short-circuiting lets you write guards that would otherwise throw:
const user = null;
console.log(user && user.name); // null: user.name is never read, so no TypeError
const admin = { name: 'Ada' };
console.log(admin && admin.name); // 'Ada'A later chapter covers optional chaining (?.), which replaces most obj && obj.prop guards. The && form still shows up all over existing code, so you need to be able to read it.
You can also use && to run something conditionally, as in isReady && start(). This works, but an if statement is usually clearer when the expression exists only for its side effect.
The ! Operator and the !! Idiom
! converts its operand to a boolean with ToBoolean and then inverts it. Applying it twice gives the plain boolean truthiness of a value.
console.log(!''); // true
console.log(!NaN); // true
console.log(!{}); // false: every object is truthy
console.log(!!'hello'); // true
console.log(!![]); // true: an empty array is still an object
console.log(!!0); // false
console.log(Boolean(0) === !!0); // true: same conversionUse !!value or Boolean(value) when you need a real boolean, for example in a JSON payload or a function that promises to return true or false:
function hasItems(list) {
return !!(list && list.length); // without !!, this could return undefined, null, or 0
}
console.log(hasItems([1, 2])); // true
console.log(hasItems([])); // false
console.log(hasItems(null)); // falsePrecedence Among the Logical Operators
The three operators have different precedence: ! binds tightest, then &&, then ||. All of them bind more loosely than comparisons, so a > 1 && b < 2 groups the way you would expect.
console.log(true || false && false); // true: parsed as true || (false && false)
console.log(false && true || true); // true: parsed as (false && true) || true
console.log(!0 && 'x'); // 'x': parsed as (!0) && 'x'
console.log(!(0 && 'x')); // trueWhen you mix && and ||, add parentheses even if precedence already produces the grouping you want. Readers should not have to recall the precedence table. When you combine ?? with && or ||, parentheses are required, as the next chapter explains.
De Morgan's laws let you rewrite negated conditions, and they hold for the truthiness of the results:
const a = 0, b = 'x';
console.log(!(a && b) === (!a || !b)); // true
console.log(!(a || b) === (!a && !b)); // trueCommon Errors
Falsy Defaults Get Overwritten
The most common bug is using || to supply a default when 0, '', or false are valid inputs.
function setVolume(v) {
return v || 50;
}
console.log(setVolume(0)); // 50: the caller asked for silence and got 50
console.log(setVolume(20)); // 20|| cannot tell "missing" apart from "falsy". If only null and undefined mean "missing", use ??, which the next chapter covers.
Leaking Non-Boolean Results
count && 'You have messages' evaluates to 0 when count is 0. If the code then displays that result, the user sees a stray 0. UI templates that render whatever value an expression produces hit this often. Make the condition a real boolean, such as count > 0 && ....
const count = 0;
console.log(count && 'You have messages'); // 0
console.log(count > 0 && 'You have messages'); // falseAssuming the Result Is a Boolean
Strict comparisons against true fail when the result is an operand:
const name = 'Ada';
const flag = name && name.length; // 3, not true
console.log(flag === true); // false
console.log(!!flag === true); // trueExpecting Both Sides to Run
A function call on the right of && or || is conditional. Don't put required work there, such as logging, validation, or cleanup.
Exercise
What do these expressions evaluate to? (a) '' || null || 0 (b) [] && 'x' (c) !!'0' (d) 0 || false && 'y'
Show answer
(a) 0, because no operand is truthy, so || returns the last one. (b) 'x', because [] is truthy (it is an object), so && returns the right operand. (c) true, because '0' is a non-empty string and therefore truthy. (d) false. It parses as 0 || (false && 'y'). The inner && returns false, and since 0 is falsy, || returns that false.
Exercise
The function below should return the configured page size, defaulting to 25 when the option is missing. Explain the bug and fix it without using ??. function pageSize(opts) { return opts.size || 25; }
Show answer
When opts.size is 0, || treats it as falsy and returns 25, so a caller can never set size 0. Check for missing values explicitly instead: function pageSize(opts) { return opts.size === undefined || opts.size === null ? 25 : opts.size; }. This keeps 0 and replaces only undefined and null. The next chapter's ?? operator expresses the same thing more briefly.
Exercise
How many times is 'called' printed, and what is the value of result? function f(v) { console.log('called'); return v; } const result = f(1) && f(0) && f(2);
Show answer
'called' is printed twice. f(1) returns 1, which is truthy, so f(0) runs and returns 0, which is falsy. && stops there, f(2) is never called, and result is 0.