There are 2 Short Circuit Conditionals in JavaScript first using &&
(And logic) and another one is Evaluation with ||
(OR logic).
Logical AND (&&)
The logical AND (&&
) operator (logical conjunction) for a set of boolean operands will be true
if and only if all the operands are true
. Otherwise, it will be false
.
expr1 && expr2
Logical OR (||)
The logical OR (||
) operator (logical disjunction) for a set of operands is true if and only if one or more of its operands is true. I
expr1 || expr2
Short circuit in JavaScript
A simple example code is evaluating an AND expression (&&), if the first operand is false, JavaScript will short-circuit and not even look at the second operand.
true && true
// true
true && false
// false
false && false
// false
Code
<!DOCTYPE html>
<html>
<body>
<script>
const a = 3;
const b = -2;
console.log(a > 0 && b > 0);
</script>
</body>
</html
>
Output:
Expressions – Logical OR
const a = 3;
const b = -2;
console.log(a > 0 || b > 0);
// expected output: true
Does JavaScript have a “Short-circuit” evaluation?
Answer: Yes, JavaScript has a “short-circuit” evaluation like && Operator in C#.
(some falsy expression) && expr
will evaluate to falsy expression(some truthy expression) || expr
will evaluate to a truthy expression
if (true == true || foo.foo){
// Passes, no errors because foo isn't defined.
}
Do comment if you have any doubts or suggestions on this JS short circuit topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version