Using the switch Structure : Switch « Statement « JavaScript Tutorial






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>








3.5.Switch
3.5.1.Using the switch Structure
3.5.2.Use switch statement to deal with form input value
3.5.3.Switch statement with return value from a prompt dialog
3.5.4.Switch statement with default value
3.5.5.Switch with boolean value
3.5.6.Switch Statement with Integer as the control variable
3.5.7.Switch Statement with calculation