JavaScript offers the switch statement as an alternative to using the if...else structure. | |
The switch statement is useful when testing all the possible results of an expression. | |
The format of a switch structure looks like the following: | |
| |
The switch statement evaluates an expression placed between parentheses. | |
The result is compared to labels associated with case structures that follow the switch statement. | |
If the result is equal to a label, the statement(s) in the corresponding case structure are executed. | |
A default is used at the end of a switch structure to catch results that do not match any of the case labels. | |
A colon always follows a label. | |
Curly brackets {} are used to hold all the case structures together, but they are not used within a case structure. | |
The keyword break is used to break out of the entire switch statement once a match is found, thus preventing the default structure from being executed accidentally. | |
|