switch( ... ) ... case: ... default: ... (Selector)

Select one of a set of cases according to a switch value.

Availability:

ECMAScript edition - 3
JavaScript - 1.2
JScript - 3.0
Internet Explorer - 4.0
Netscape - 4.0
Netscape Enterprise Server - 3.0
JavaScript syntax:-switch(aValue) { aCaseTree }
Argument list:aCaseTreeA set of case statements to be selected.
aValueAn integer value used as a selector

The switch statement evaluates its expression and selects a labeled statement block for execution according to the value resulting from the expression.

If there is no match, then a default case is used.

Each labeled case should be terminated by a break keyword to avoid the execution dropping down through into the handler for the next case in the script source. On the other hand, this may be what you intend and so omitting the break keyword allows several cases to be matched and handled with a common fragment of code.

The use of switch is illustrated in the example. The value enclosed in parentheses is evaluated and its result is used as a selector. It looks for a matching case label and executes the code in that block. If it does not match, it uses the default block (if there is one).

Unlike the ANSI C version of switch, the JavaScript one will match strings as well as integers.

The break; statements prevent the code from dropping down into the next block.

The following are all legal case labels:

case 0:

case 100*23:

case "abc":

case "aaa" + "bbb":

case Number.NaN:

The C language environment dictates that a switch statement must be capable of supporting at least 256 individual cases. The ECMAScript standard does not define a limit.

You need to be careful when nesting switch statements. The case labels will be subordinate to the closest enclosing switch given the rules of precedence and block structuring of the code. Case labels must be unique within a single switch mechanism, but can duplicate case values in other switch structures within the same or an enclosing code block.

Warnings:

Example code:

   // An example switch statement

   switch(myValue)

   {

      case 1:      document.write("one");

      break;

      case 'too':  document.write("two");

      break;

      default:     document.write("unknown");

      break;

   }

See also:break, Colon (:), else ..., Flow control, if( ... ) ..., if( ... ) ... else ..., Selection statement

Cross-references:

ECMA 262 edition 2 - section 7.4.3

ECMA 262 edition 3 - section 7.5.2

ECMA 262 edition 3 - section 12.11