JavaScript Switch Statement

The switch statement is used to perform different actions based on different expression. The switch statement basically evaluates a switch expression, and based on the switch expression value when the case matched then the associated block of code is executed until break statement or end case statement. And if there is no matched case then the code associated with default will be executed. Syntax :
switch (expression) {
  case value_1:
    code to be executed if expression = value_2
    break;
  case value_2:
    code to be executed if expression = value_2
    break;
  ........... 
  ........... 
  case value_n:
    code to be executed if expression = value_n
    break;

  default:
    code to be executed if none of values are matched
}
The break statements indicate the end of a particular case. If they were omitted, the interpreter would continue executing each statement in each of the following cases. The basic example of switch statement is as follows :
<!DOCTYPE html>
<html>
<head>
  <title>Switch Case</title>
</head>
<body>
  <script>
    function ifElseifElse_statement() {
      text = document.getElementById("demo");
      var num = prompt("Enter Number between 1 to 7 : ");
      switch (num) {
        case '1':
          text.innerText = "The 1st day in Monday.";
          break;
        case '2':
          text.innerText = "The 2nd day in Tuesday.";
          break;
        case '3':
          text.innerText = "The 3rd day in Wednesday.";
          break;
        case '4':
          text.innerText = "The 4th day in Thursday.";
          break;
        case '5':
          text.innerText = "The 5th day in Friday.";
          break;
        case '6':
          text.innerText = "The 6th day in Satuarday.";
          break;
        case '7':
          text.innerText = "The 7th day in Sunday.";
          break;
        default:
          text.innerText = "Please Enter number between 1 to 7.";
      }
    }
  </script>
  <button type="button" onclick="ifElseifElse_statement()">Click Here</button>
  <p id="demo"></p>
</body>
</html>
Output :




Next Topic :