JavaScript Switch Statement


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


JavaScript switch Statement

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

Grammar

switch(n)
{
     case 1:
         // Execute code block 1
         break;
     case 2:
         // Execute code block 2
         break;
     default:
         // Code executed at different time from case 1 and case 2
}

How it works: First set the expression n (usually a variable). 

The value of the expression will then be compared with the value of each case in the structure. If there is a match, the code block associated with the case will be executed. Please use break to prevent the code from automatically running to the next case.

Example

Shows today's week name. Please note that Sunday=0, Monday=1, Tuesday=2, etc.:

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

The x result is: Today is Sunday.

 Try It! 


default Keyword

Please use the default keyword to specify what to do when the match does not exist:

Example

If today is not Saturday or Sunday, the default message will be output:

var d=new Date().getDay();
switch (d)
{
     case 6:x="Today is Saturday";
     break;
     case 0:x="Today is Sunday";
     break;
     default:
     x="Looking forward to the weekend";
}
document.getElementById("demo").innerHTML=x;

The x result is: Looking forward to the weekend

 Try It!