JS Short Circuit Evaluation
In this page:
AND Short Circuit
&& evaluates left to right and stops as soon as it hits a falsy value, since the overall result is already determined. The right-hand expression is never evaluated in that case.
Example: AND Short Circuit
console.log(false && console.log("never runs"));
OR Short Circuit
|| stops as soon as it hits a truthy value, since that value alone determines the result. This 'short circuit' behavior means the second operand isn't always executed.
Example: OR Short Circuit
console.log(true || console.log("never runs"));
Short Circuit Function Calls
Because JavaScript skips evaluating the right side once the result is known, you can use && to conditionally call a function: isReady && doSomething() only calls doSomething if isReady is truthy.
Example: Short Circuit Function Calls
const isReady = true;
isReady && console.log("Doing something");
Default Values
|| is commonly used to supply a fallback: const name = input || Guest uses input if it's truthy, otherwise falls back to Guest — though ?? is often safer for numeric/boolean defaults.
Example: Default Values
const input = "";
const name = input || "Guest";
console.log(name);
Short Circuit Evaluation Rules
The short-circuit rule is what lets you chain multiple && or || conditions efficiently: evaluation stops the instant the final outcome is already decided, skipping unnecessary work.
Example: Short Circuit Evaluation Rules
const a = false, b = true, c = true;
console.log(a && b && c); // stops at a
console.log(a || b || c); // stops at b
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: