The switch statement is used to perform different actions based on different conditions.
Use the switch statement to select one of many blocks of code to be executed.
This is how it works:
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:
The result of day will be:
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.
The default keyword specifies the code to run if there is no case match:
The getDay() method returns the weekday as a number between 0 and 6.
If today is neither Sunday (6) nor Saturday (0), write a default message:
The result of text will be:
Sometimes, in a switch block, you will want different cases to use the same code, or fall-through to a common default.
Note from the next example, that cases can share the same code block, and that the default case does not have to be the last case in a switch block:
|If default is not the last case in the switch block, remember to end it with a break.|