In JavaScript’s short circuit feature, an expression is evaluated from left to right until it is confirmed that the results of the remaining conditions will not affect the already evaluated result. If the result is clear even before the expression is fully evaluated, this is ignored, and the result is returned. Short circuit assessment avoids unnecessary work and leads to effective treatment.
Please Check all JavaScript articles HERE. For more such post you can refer HERE.
AND (&&) short circuit: In the case of AND, the expression is evaluated until we get a false result because the result will always be false, regardless of other conditions. If there is an expression with && (logical AND) and the first operand is false then a short circuit occurs, the additional expression is not evaluated and false is returned. Shortening JavaScript is also useful because it can be used to replace if else statements. In JavaScript, the expression true && always evaluates to expression and the expression false && always evaluates to false, regardless of whether the expression returns true/false or not.
Example: Below is an example of the short-circuiting operators.
JavaScript
<script>     function test() {         // AND short circuit         console.log( false && true )         console.log( true && true )         // OR short circuit         console.log( true || false )         console.log( false || true )     }     test(); </script> |
Output:
false true true true
 Example: Short-circuiting using AND (&&) operator.
JavaScript
<script>     // Since first operand is false and operator     // is AND, Evaluation stops and false is     // returned.     console.log( false && true && true && false )         // Whole expression will be evaluated here.     console.log( true && true && true ) </script> |
Output:
false true
OR(||) short circuit: In the case of OR, the expression is evaluated until we get a true result because the result will always be true, regardless of other conditions. If there is an expression with || (logical OR) and the first operand itself is true, a short circuit occurs, evaluation stops, and the return value is true. The abbreviation OR can also be used to replace if else statements, just like the abbreviation AND in JavaScript. In JavaScript, the expression true|| always returns true and false || expression always returns expression.
Example: Short-circuiting using OR(||).
JavaScript
<script> Â Â Â Â // First operand is true and operator is ||, Â Â Â Â // evaluation stops and true is returned. Â Â Â Â console.log( true || false || false ) Â Â Â Â Â Â Â Â // Evaluation stops at the second operand(true). Â Â Â Â console.log( false || true || true || false ) </script> |
Output:
true true
We have a complete list of JavaScript Operators, to check those please go through the JavaScript Operators Complete Reference article.