ES6 - Logical operators
Assume the value of variable A is 10 and B is 20.
Example
var avg = 20;
var percentage = 90;
console.log("Value of avg: " + avg + " ,value of percentage: " + percentage);
var res = ((avg > 50) && (percentage > 80));
console.log("(avg>50)&&(percentage>80): ", res);
var res = ((avg > 50) || (percentage > 80));
console.log("(avg>50)||(percentage>80): ", res);
var res = !((avg > 50) && (percentage > 80));
console.log("!((avg > 50)&&(percentage>80)): ", res);
The following output is displayed on successful execution of the above code.
Value of avg: 20 ,value of percentage: 90 (avg > 50)&&(percentage > 80): false (avg > 50)||(percentage > 80): true !((avg > 50)&&(percentage > 80)): true
Short-circuit Operators
The && and || operators are used to combine expressions.
The && operator returns true only when both the conditions return true. Let us consider an expression −
var a = 10 var result = ( a<10 && a>5)
In the above example, a<10 and a>5 are two expressions combined by an && operator. Here, the first expression returns false. However, the && operator requires both the expressions to return true. So, the operator skips the second expression.
The || operator returns true, if one of the expressions return true. For example −
var a = 10 var result = ( a>5 || a<10)
In the above snippet, two expressions a>5 and a<10 are combined by a || operator. Here, the first expression returns true. Since, the first expression returns true, the || operator skips the subsequent expression and returns true.
Due to this behavior of the && and || operator, they are called as short-circuit operators.