JavaScript Switch Case


The switch statement is used to perform different action based on different conditions.

Use the switch statement to select one of many blocks of code to be executed.

switch(expression) {
    case n:
        code block
        break;
    case n:
        code block
        break;
    default:
        default code block
}
How it works:
  • The switch expression is evaluated once.
  • The value of the expression is compared with the values of each case.
  • If there is a match, the associated block of code is executed.

Example

<script type="text/javascript">
  var x = new Date();
  var month =x.getMonth()
  switch (month) {
    case 0:
        month = "January";
        break;    
    case 1:
        month = "February";
        break;
    case 2:
        month = "March";
        break;
    case 3:
        month = "April";
        break;
    case 4:
        month = "May";
        break;
    case 5:
        month = "June";
        break;
    case 6:
        month = "July";
        break;
    case 7:
        month = "August";
        break;
    case 8:
        month = "September";
        break;
    case 9:
        month = "October";
        break;
    case 10:
        month = "November";
        break;
    case 11:
        month = "December";
        break;
}
document.write(month);
</script>
Output

The break Keyword

When the JavaScript code interpreter reaches a break keyword, it breaks out of the switch block.

This will stop the execution of more execution of code and/or case testing inside the block.


The default Keyword

The default keyword specifies the code to run if there is no case match.

Example

<script type="text/javascript">
   var grade='E';
   switch (grade)
   {
    case 'A': document.write("Good job");
            break;
    case 'B': document.write("Pretty good");
            break;
    case 'C': document.write("Passed");
            break;
    case 'D': document.write("Not so good");
            break;
    case 'F': document.write("Failed");
            break;
    default:  document.write("Unknown grade")
}
</script>
Output
Unknown grade

Common Code and Fall-Through

In a switch block, you will want different cases to use the same code, or fall-through to a common default.

Example

<script type="text/javascript">
   var reg = 11211855;
   switch (reg)
   {
    case 11211855:
    case 11211401:
    case 11211854: document.write("Jk201");
            break;
    case 11211155:
    case 11211201:
    case 11211454: document.write("Jk202");
            break;
    default:  document.write("Not Match")
}
</script>
Output
Jk201

Share this article on