Logical Operators in JavaScript

Logical operators in JavaScript, are used to connect multiple expressions to evaluate and return boolean value (true/false). For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <script>
      var a = 10, b = 20, c = 30, large;
      if(a>b && a>c) {
         large = a;
      }
      else if(b>a && b>c) {
         large = b;
      }
      else {
         large = c;
      }
      document.write("Largest = ", large);
   </script>
   
</body>
</html>
Output

List of All Logical Operators in JavaScript

  • Logical OR (||)
  • Logical AND (&&)
  • Logical NOT (!)

JavaScript Logical OR (||) Operator

The || operator returns true, if any of the expression evaluates to be true. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <script>
      var x = 10, y = 12, z = 11, res;
      res = x>y || y>z;
      document.write(res);
   </script>
   
</body>
</html>
Output

In above example, since the first expression, that is x>y or 10>12 evaluates to be false, but the second expression, that is y>z or 12>11 evaluates to be true, therefore true will be initialized to res variable.

JavaScript Logical AND (&&) Operator

The && operator returns true, if all the expressions evaluates to be true. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <script>
      var x = 10, y = 12, z = 11, res;
      res = z>x && y>z;
      document.write(res);
   </script>
   
</body>
</html>
Output

JavaScript Logical NOT (!) Operator

The ! operator reverses the boolean value. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <script>
      var x = 10, y = 12, z = 11, res;
      res = !(z>x && y>z);
      document.write(res);
   </script>
   
</body>
</html>
Output

JavaScript Online Test


« Previous Tutorial Next Tutorial »