< Javascript Tutorial

Javascript switch

← Previous Next →


The switch statement is used to select one of many blocks of code to be executed.

Syntax

switch(expression) {
   case n:
      code block
   break;
   case n:
      code block
   break;
   default:
      default code block
}

This is 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

The getDay() method returns the weekday as a number between 0 and 6. (Sunday=0, Monday=1, Tuesday=2 ..)
Use the weekday number to calculate weekday name:

switch (new Date().getDay()) {
   case 0:
      day = "Sunday";
   break;
   case 1:
      day = "Monday";
   break;
   case 2:
      day = "Tuesday";
   break;
   case 3:
      day = "Wednesday";
   break;
   case 4:
      day = "Thursday";
   break;
   case 5:
      day = "Friday";
    break;
   case 6:
      day = "Saturday";
    break;
}

The result of day will be:
Sunday


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 code and case testing inside the block.
Note :  When a match is found, and the job is done, it's time for a break.
There is no need for more testing.

← Previous Next →