Core JavaScript 1.5 Reference:Statements:switch
From MDC
Contents |
[edit] Summary
Evaluates an expression, matching the expression's value to a case label, and executes statements associated with that case.
| Statement | |
| Implemented in: | JavaScript 1.2, NES 3.0 |
| ECMA Version: | ECMA-262, Edition 3 |
[edit] Syntax
switch (expression) {
case label1:
statements1
[break;]
case label2:
statements2
[break;]
...
case labelN:
statementsN
[break;]
default:
statements_def
[break;]
}
[edit] Parameters
-
expression - An expression matched against each label.
-
labelN - Identifier used to match against
expression.
-
statementsN - Statements that are executed if
expressionmatches the associated label.
-
statements_def - Statements that are executed if
expressiondoes not match any label.
[edit] Description
If a match is found, the program executes the associated statements. If multiple cases match the provided value, the first case that matches is selected, even if the cases are not equal to each other.
The program first looks for a case clause with a label matching the value of expression and then transfers control to that clause, executing the associated statements. If no matching label is found, the program looks for the optional default clause, and if found, transfers control to that clause, executing the associated statements. If no default clause is found, the program continues execution at the statement following the end of switch. By convention, the default clause is the last clause, but it does not need to be so.
The optional break statement associated with each case label ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. If break is omitted, the program continues execution at the next statement in the switch statement.
[edit] Examples
[edit] Example: Using switch
In the following example, if expression evaluates to "Bananas", the program matches the value with case "Bananas" and executes the associated statement. When break is encountered, the program breaks out of switch and executes the statement following switch. If break were omitted, the statement for case "Cherries" would also be executed.
switch (expr) {
case "Oranges":
document.write("Oranges are $0.59 a pound.<br>");
break;
case "Apples":
document.write("Apples are $0.32 a pound.<br>");
break;
case "Bananas":
document.write("Bananas are $0.48 a pound.<br>");
break;
case "Cherries":
document.write("Cherries are $3.00 a pound.<br>");
break;
case "Mangoes":
case "Papayas":
document.write("Mangoes and papayas are $2.79 a pound.<br>");
break;
default:
document.write("Sorry, we are out of " + expr + ".<br>");
}
document.write("Is there anything else you'd like?<br>");