Sub topic 7
Short-Circuit Evaluation: When the Right Side Never Runs
This chapter assumes you can declare variables with let and const, write and call functions, read console.log output, and predict which operand && and || return (covered in the two previous chapters). Here the question changes. Earlier chapters asked which value comes back. This chapter asks which code actually runs.
The Rule in One Sentence
JavaScript evaluates the left operand of && or || first. If that value alone decides the result, the right operand is never evaluated.
- For
A && B: ifAis falsy, the result isAandBis skipped. - For
A || B: ifAis truthy, the result isAandBis skipped.
"Skipped" means the right side is never run at all. Its function calls never happen. Its property lookups never happen. Its errors are never thrown. JavaScript does not compute the right side and then throw the result away.
Proving the Right Side Is Skipped
The clearest test is a function that logs when it is called. If nothing is logged, the function never ran.
function log(msg) {
console.log(msg);
return msg;
}
false && log("skipped"); // nothing is logged
true || log("skipped"); // nothing is logged
true && log("runs"); // logs "runs"
false || log("also runs"); // logs "also runs"In the first two lines the left operand already decides the result. false && anything must be falsy, and true || anything must be truthy, so JavaScript never calls log. In the last two lines the left operand does not decide anything, so the right side has to run.
Chains Stop at the First Deciding Operand
A chain such as a && b && c groups from the left, as (a && b) && c. The practical effect is that JavaScript walks left to right and stops at the first operand that decides the result.
function check(name, result) {
console.log(`checking ${name}`);
return result;
}
const allOk = check("a", true) && check("b", false) && check("c", true);
console.log(allOk);
// checking a
// checking b
// false
const anyOk = check("x", false) || check("y", true) || check("z", true);
console.log(anyOk);
// checking x
// checking y
// trueIn the && chain, check("c", ...) never runs because b was already falsy. In the || chain, check("z", ...) never runs because y was already truthy. A long chain is a sequence of gates, and evaluation ends at the first one that fails for && or passes for ||.
What "Never Evaluated" Covers
Skipping the right operand skips everything inside it. Several kinds of work can sit in that expression without being obvious.
| Inside the right operand | Effect when short-circuited |
|---|---|
| Function call `f()` | `f` is not called; its side effects do not happen |
| Property read `obj.prop` | The read never happens, so no TypeError on `null` and getters do not run |
| Increment `count++` | `count` is not changed |
| `await promise` | The `await` does not run; the async function does not pause there |
| An expression that throws | No exception is raised |
Getters show this clearly because a property read can run code:
const report = {
get total() {
console.log("computing total");
return 42;
},
};
const showTotal = false;
const value = showTotal && report.total;
console.log(value); // false, and "computing total" is never loggedErrors are skipped the same way. This is the basis of the classic null guard:
const config = null;
const enabled = config !== null && config.enabled;
console.log(enabled); // false, no TypeErrorWithout short-circuiting, config.enabled would throw TypeError: Cannot read properties of null. Because the left side is false, that read never runs. A later chapter covers optional chaining (?.), which does this job more directly.
Using Short-Circuiting on Purpose
Conditional calls
condition && action() runs action only when condition is truthy. It works like a one-line if.
const debug = true;
const isOffline = false;
debug && console.log("debug mode on"); // logs
isOffline && console.log("retrying later"); // nothing|| gives the opposite form: condition || action() runs action only when condition is falsy.
function fail(message) {
throw new Error(message);
}
const port = 8080;
port || fail("port is required"); // port is truthy, fail is never called
console.log("starting on", port);Skipping expensive work
Put the cheap test first and the expensive one second. The expensive test then runs only when the cheap one does not already decide the result.
let scans = 0;
function deepScan(text) {
scans++;
return text.includes("forbidden");
}
function isBlocked(text) {
return text.length > 0 && deepScan(text);
}
console.log(isBlocked("")); // false
console.log(isBlocked("hello")); // false
console.log(isBlocked("forbidden word")); // true
console.log(scans); // 2, the empty string was never scannedThe order of operands matters here. Swapping them to deepScan(text) && text.length > 0 gives the same results but runs the scan every time.
Common Errors
Relying on a side effect that may not happen
If the right operand does something important, that work happens only some of the time. This bug is easy to miss because the code looks as if both sides always run.
let attempts = 0;
function tryConnect() {
attempts++;
return false;
}
const hasCachedConnection = true;
const connected = hasCachedConnection || tryConnect();
console.log(connected, attempts); // true 0If the code later assumes attempts counts every pass through this line, it is wrong. The same trap appears in if (save() && notify()): when save() returns a falsy value, notify() never runs. If both must run, call them as separate statements first and then combine the results:
function save() { console.log("saving"); return false; }
function notify() { console.log("notifying"); return true; }
const saved = save();
const notified = notify();
if (saved && notified) {
console.log("all done");
}
// saving
// notifyingConfusing && and || with & and |
The single-character operators & and | are bitwise operators. They convert both operands to numbers and always evaluate both sides.
let calls = 0;
function bump() {
calls++;
return true;
}
false && bump(); // bump skipped
false & bump(); // bump runs, result is 0
true || bump(); // bump skipped
true | bump(); // bump runs, result is 1
console.log(calls); // 2A missing character changes both the result type (a number instead of an operand) and whether the right side runs.
Expecting ! to short-circuit
! has only one operand, so it has nothing to skip. !expensive() always calls expensive. Only the binary logical operators (&&, ||, and ??, which comes later) and the conditional operator short-circuit.
Short-Circuiting with await
When the right operand contains await, short-circuiting decides whether the function pauses at all.
function fetchProfile() {
console.log("fetching");
return Promise.resolve({ name: "Ada" });
}
async function load(loggedIn) {
const profile = loggedIn && (await fetchProfile());
console.log("profile:", profile);
}
load(false).then(() => load(true));
// profile: false
// fetching
// profile: { name: 'Ada' }For load(false), fetchProfile is never called and no request starts. Keep that in mind when the network call itself is a side effect you rely on, such as a call that records a visit.
Exercise
What does this code log, in order? function t(n) { console.log("t" + n); return n; } const r = t(0) || t(2) && t(0) || t(3); console.log(r);
Show answer
&& binds tighter than ||, so this reads as t(0) || (t(2) && t(0)) || t(3). First t(0) logs "t0" and returns 0, which is falsy, so evaluation continues. Then t(2) logs "t2" and returns 2, which is truthy, so && evaluates t(0), which logs "t0" and returns 0. The left part is now 0, which is falsy, so t(3) runs, logs "t3" and returns 3. The output is t0, t2, t0, t3, then 3.
Exercise
A developer writes if (validate(form) && submit(form)) showSuccess(); and reports that submit "sometimes doesn't run". Explain why, and say whether this is a bug.
Show answer
submit(form) runs only when validate(form) returns a truthy value. When validation fails, && short-circuits and submit is never called. That is usually the intended behavior, because you should not submit an invalid form. It is a bug only if submit was expected to run every time. In that case, call it as a separate statement.
Exercise
Why does let n = 0; false & (n++ > -1); console.log(n); log 1, while the same line with && logs 0?
Show answer
& is the bitwise AND operator. It always evaluates both operands, so n++ runs and n becomes 1. && is the logical AND operator. It sees that false is falsy, returns it, and never evaluates n++, so n stays 0.