AND(&&) short circuit

In the case of AND, the expression is evaluated until we get one false result because the result will always be false, independent of the further conditions. If there is an expression with &&(logical AND), and the first operand itself is false, then a short circuit occurs, the further expression is not evaluated and false is returned. JavaScript short-circuiting is also very useful because it may be used to replace if else statements. In JavaScript true && expression always evaluates to expression and false && expression always evaluates to false, no matter whether the expression returns a true/false value or not.

Example 1: Below is an example of the Short circuiting operators.

javascript




function gfg() {
    // AND short circuit
    console.log(false && true)
    console.log(true && true)
    // OR short circuit
    console.log(true || false)
    console.log(false || true)
}
gfg();


Output

false
true
true
true

 Example 2: Short-circuiting using the AND(&&) operator. 

javascript




// 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.
console.log(true && true && true)


Output

false
true

Javascript Short Circuiting Operators

In JavaScript short-circuiting, an expression is evaluated from left to right until it is confirmed that the result of the remaining conditions is not going to affect the already evaluated result. If the result is clear even before the complete evaluation of the expression, it short circuits and the result will be returned. Short circuit evaluation avoids unnecessary work and leads to efficient processing. 

There are two types of short circuits:

Table of Content

  • AND(&&) short circuit
  • OR(||) short circuit

Similar Reads

AND(&&) short circuit

In the case of AND, the expression is evaluated until we get one false result because the result will always be false, independent of the further conditions. If there is an expression with &&(logical AND), and the first operand itself is false, then a short circuit occurs, the further expression is not evaluated and false is returned. JavaScript short-circuiting is also very useful because it may be used to replace if else statements. In JavaScript true && expression always evaluates to expression and false && expression always evaluates to false, no matter whether the expression returns a true/false value or not....

OR(||) short circuit

...

Contact Us