logical operator is mostly used to make decisions based on conditions specified for the statements. It can also be used to manipulate a boolean or set termination conditions for loops.
- !(NOT): Converts operator to boolean and returns flipped value
- &&:(AND) Evaluates operands and return true only if all are true
- ||(OR): Returns true even if one of the multiple operands is true
NOT(!) Operator: It reverses the boolean result of the operand (or condition). It Converts the operand to boolean type i.e true/false
result = !value; // Can have single argument
Example: The operator converted the value ‘1’ to a boolean and it resulted in ‘true’ then after it flipped(inversed) that value and that’s why when we finally alert the value we get ‘false’.
let geek = 1;
AND(&&) Operator: It accepts multiple arguments and it evaluates the operands from left to right. And for each operand, it will first convert it to a boolean. If the result is false, stops and returns the original value of that operand. Otherwise, if all were truthy it will return the last truthy value.
result = a && b; // Can have multiple arguments.
Example: The operator checks for the values from left to right and returns the value if the result is false and if the result is true it will return the last value.
console.log( 0 && 1 );
console.log( 1 && 3 );
console.log( 1 && 2 && 3 && 4);
OR(||) Operator: The ‘OR’ operator is somewhat opposite of the ‘AND’ operator. It evaluates the operand from left to right. And for each operand, it will first convert it to a boolean. If the result is true, stops and returns the original value of that operand. Otherwise, if all the values are false, it will return the last value./p>
result = a || b;
Example: The operator checks the values from left to right and if the result is true returns the original value and if false returns the last value of operands.
console.log( 0 || 1 );
console.log( 1 || 3 );
console.log( -1 || -2 || -3 || -4);