JavaScript switchStatements
The switch statement is used to perform different actions based on different conditions.
JavaScript switch Statement
Use the switch statement to select one of the multiple code blocks to execute.
Syntax
switch(n)
{
case 1:
Execute code block1
break;
case 2:
Execute code block2
break;
default:
fromcase 1andcase 2Code executed when different}
How it works: First set the expressionn(usually a variable). Then the value of the expression is compared with the value of each case in the structure. If there is a match, the code block associated with that case is executed. Usebreak to prevent the code from automatically running to the next case.
Example
Display today's weekday name. 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;
}
xOutput:
Try it yourself »
The default Keyword
Use the default keyword to specify what to do when a match does not exist:
Example
If today is not Saturday or Sunday, a 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;
xOutput:
Try it yourself »