Sub topic 13
&&, ||, and ! as Value Selectors
This chapter assumes you know which values are truthy and falsy, and that you have seen how precedence groups operators. In many languages, logical operators always return true or false. In JavaScript, && and || return one of their operands. Only ! always returns a boolean.
The Working Model
Each binary logical operator checks the truthiness of its left operand and then returns one of the two operands unchanged:
| Expression | If `a` is truthy | If `a` is falsy | Column | Column |
|---|---|---|---|---|
| `a && b` | returns `b` | returns `a` | ||
| `a \ | \ | b` | returns `a` | returns `b` |
| `!a` | returns `false` | returns `true` |
The operators convert a to a boolean only to make this decision. The value they return is never converted.
console.log('a' && 'b'); // 'b'
console.log(0 && 'b'); // 0
console.log('' || 'fallback'); // 'fallback'
console.log('x' || 'fallback'); // 'x'
console.log(!'text'); // false
console.log(!!'text'); // true: double negation converts to a booleanShort-Circuit Evaluation
The right operand runs only when it is needed. That is why && works as a guard and || works as a fallback.
function trace(label, value) {
console.log('evaluated', label);
return value;
}
trace('left', 0) && trace('right', 1);
// prints only: evaluated left
trace('left', 'ok') || trace('right', 1);
// prints only: evaluated left
const user = null;
const name = user && user.name; // no TypeError, because user.name is never read
console.log(name); // nullPrecedence Among the Three
! binds tightest, then &&, then ||. So a || b && c means a || (b && c), and !a && b means (!a) && b.
console.log(true || false && false); // true: true || (false && false)
console.log((true || false) && false); // false
console.log(!0 && 'yes'); // 'yes': (!0) is trueCommon Errors
- Using
||for defaults when0or''is valid.port || 8080replaces a real0with8080. The next chapter covers??, which avoids this. - Expecting a boolean back.
const isReady = items.length && loaded;gives0when the list is empty, notfalse. Use!!orBoolean()when you need an actual boolean. - Writing
!a == band meaning!(a == b). Because!binds first, this compares!awithb.
const items = [];
const loaded = true;
console.log(items.length && loaded); // 0
console.log(!!(items.length && loaded)); // false
const port = 0;
console.log(port || 8080); // 8080, probably not what you wantedExercise
What does each line log? (a) console.log(null || 0 || 'z'); (b) console.log(1 && '' && 'z'); (c) console.log(!'' || 'n');
Show answer
(a) 'z': null and 0 are falsy, so || moves on to the last operand. (b) '': 1 is truthy, '' is falsy, so && stops at '' and returns it. (c) true: !'' is true, so || returns it without evaluating 'n'.
Exercise
A function returns config.timeout || 5000. A caller passes { timeout: 0 } to turn off the timeout. What goes wrong, and how can you see it from the operator's rule?
Show answer
0 is falsy, so || returns the right operand, 5000. The caller's explicit 0 is silently replaced by the default. A fallback that triggers only on null or undefined is needed instead.