JavaScript Conditional Statements

Conditional (decision making) statements in JavaScript, are used to perform action based on the condition. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <p id="xyz"></p>

   <script>
      let x = 10;
      if(x%2 == 0)
         document.getElementById("xyz").innerHTML = "Even number";
      else
         document.getElementById("xyz").innerHTML = "Odd number";
   </script>
   
</body>
</html>
Output

That is, in above example, if the condition x%2 == 0 evaluates to be true, then the statement of if block will be executed, otherwise the statement of else block will be executed.

List of Conditional Statements in JavaScript

  1. if Statement
  2. if...else Statement
  3. switch Statement

JavaScript Conditional Statements Example

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <button onclick="greet()">Greeting</button>
   <p id="myPara"></p>
   <script>
      function greet()
      {
         let tn, g;

         tn = new Date().getHours();

         if(tn<9 && tn>4)
            g = "Good Morning";
         else if(tn>15 && tn<21)
            g = "Good Evening";
         else
            g = "Have a Good Day";
            
         document.getElementById("myPara").innerHTML = g;
      }
   </script>
   
</body>
</html>
Output

JavaScript Online Test


« Previous Tutorial Next Tutorial »



Like/Share Us on Facebook 😋