JS Short Circuit Evaluation
In this page:
const result = a || b; // first truthy value
const result = a && b; // b if a is truthy
condition && doSomething();
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.
उदाहरण: 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.
उदाहरण: 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.
उदाहरण: 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.
उदाहरण: Default Values
// Declare the constant `input`, set to ""
// Declare the constant `input`, set to ""
const input = "";
// Declare the constant `name`, set to `input || "Guest"`
// Declare the constant `name`, set to `input || "Guest"`
const name = input || "Guest";
// Print `name` to the console
// Print `name` to the console
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.
उदाहरण: 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: