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:
switch (expression)
{
case label1:
statement1;
break;
case label2:
statement2;
break;
default:
statement3;
}
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.
<html>
<SCRIPT LANGUAGE='JavaScript'>
<!--
var color = "green";
switch (color)
{
case "red":
document.write("The car is red.");
break;
case "blue":
document.write("The car is blue.");
break;
case "green":
document.write("The car is green.");
break;
default:
document.write("The car is purple.");
}
//-->
</SCRIPT>
</html>