The Javascript Switch Statement: Syntax
The Javascript Switch Statement: Syntax
Use the switch statement 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:
code block
}
Example
This example uses the weekday number to calculate the weekday name:
Thursday
The switch statement is used to perform different actions based on different conditions.
Syntax
switch(expression) {
case n:
code block
break;
case n:
code block
break;
default:
code block
}
Example
The getDay() method returns the weekday as a number between 0 and 6.
This example uses the weekday number to calculate the weekday name:
Thursday
This will stop the execution of more code and case testing inside the block.
When a match is found, and the job is done, it's time for a break. There is no need for more
testing.
A break can save a lot of execution time because it "ignores" the execution of all the rest of the
code in the switch block.
It is not necessary to break the last case in a switch block. The block breaks (ends) there anyway.
Example
If today is neither Saturday (6) nor Sunday (0), write a default message:
The default case does not have to be the last case in a switch block:
Example
If default is not the last case in the switch block, remember to end the default case with a break.
Common Code Blocks
Sometimes you will want different switch cases to use the same code.
In this example case 4 and 5 share the same code block, and 0 and 6 share another code block:
Example