Show List

JavaScript Conditional Statements


Conditional statements in JavaScript allow you to execute different code blocks based on whether a condition is true or false. The two main types of conditional statements are if and switch statements.

If..else if ..else

If statement evaluates an expression and based on whether it is true or false a set of statement is executed.
<!DOCTYPE html>
<html>

<head>
  <script>
    function demo() {
      var output = "";
      const d = new Date();
      let day = d.getDay();
     
      if (day == 1) {
        output = "Monday";
      } else if (day == 2) {
        output = "Tuesday";
      } else if (day == 3) {
        output = "Wednesday";
      } else if (day == 4) {
        output = "Thursday";
      } else if (day == 5) {
        output = "Friday";
      } else if (day == 6) {
        output = "Saturday";
      } else {
        output = "Sunday";
      }
      document.getElementById("result").innerHTML = output;
    }
  </script>
</head>

<body>

  <button type="button" onclick="demo()">Demo</button>
  <p id="result"></p>
</body>

</html>

Switch Statement

Switch statement evaluates an expression and based on the value executes block of code.
<!DOCTYPE html>
<html>

<head>
  <script>
    function demo() {
      var output = "";
      const d = new Date();
      let day = d.getDay();

      switch (day) {
        case 1:
          output = "Monday";
          break;
        case 2:
          output = "Tuesday";
          break;
        case 3:
          output = "Wednesday";
          break;
        case 4:
          output = "Thursday";
          break;
        case 5:
          output = "Friday";
          break;
        case 6:
          output = "Saturday";
        default:
          output = "Sunday";
      }
      document.getElementById("result").innerHTML = output;
    }
  </script>
</head>

<body>

  <button type="button" onclick="demo()">Demo</button>
  <p id="result"></p>
</body>

</html>

    Leave a Comment


  • captcha text