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.
Primitive values are allowed as selectors but objects, arrays and functions are not. You could wrap them with toString() or valueOf() functions though. However the results may be slightly unpredictable unless you thoroughly test the effects of those functions in all your target implementations.
The value document.forms.length is valid for use in a case label at JavaScript version 1.2 but may not be later. The values really do have to be constant, and it's possible that a later version of the interpreter may check the ReadOnly attribute of any property value that is used in this context.
// An example switch statement switch(myValue) { case 1: document.write("one"); break; case 'too': document.write("two"); break; default: document.write("unknown"); break; }
ECMA 262 edition 2 - section 7.4.3
ECMA 262 edition 3 - section 7.5.2
ECMA 262 edition 3 - section 12.11
Prev | Home | Next |
Superclasses | Up | synchronized |
JavaScript Programmer's Reference, Cliff Wootton Wrox Press (www.wrox.com) Join the Wrox JavaScript forum at p2p.wrox.com Please report problems to support@wrox.com © 2001 Wrox Press. All Rights Reserved. Terms and conditions. |