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>

   <p>Largest = <span id="xyz"></span></p>
   
   <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.getElementById("xyz").innerHTML = large;
   </script>
   
</body>
</html>
Output

Largest =

List of All Logical Operators in JavaScript

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>

   <p id="abc"></p>
   
   <script>
      var x = 10, y = 12, z = 11, res;
      res = x>y || y>z;
      document.getElementById("abc").innerHTML = 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>

   <p id="myPara"></p>
   
   <script>
      var x = 10, y = 12, z = 11, res;
      res = z>x && y>z;
      document.getElementById("myPara").innerHTML = 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>

   <p id="mp"></p>
   
   <script>
      var x = 10, y = 12, z = 11, res;
      res = !(z>x && y>z);
      document.getElementById("mp").innerHTML = res;
   </script>
   
</body>
</html>
Output

JavaScript Online Test


« Previous Tutorial Next Tutorial »