switch
An
if statement causes a branch in the flow of a
program’s execution. You can use multiple if
statements, as in the previous section, to perform a multiway branch.
However, this is not always the best solution, especially when all of
the branches depend on the value of a single variable. In this case,
it is wasteful to repeatedly check the value of the same variable in
multiple if statements.
The switch statement (implemented in JavaScript
1.2 and standardized by ECMAScript v3) handles exactly this
situation, and it does so more efficiently than repeated
if statements. The JavaScript
switch statement is quite similar to the
switch statement in Java or C. The
switch keyword is followed by an expression and a
block of code, much like the if statement:
switch(expression) {statements}
However, the full syntax of a switch statement is
more complex than this. Various locations in the block of code
are
labeled with the case keyword followed by a value
and a colon. When a switch executes, it computes
the value of expression and then looks for
a case label that matches that value. If it finds
one, it starts executing the block of code at the first statement
following the case label. If it does not find a
case label with a matching value, it starts
execution at the first statement following a special-case
default:
label. Or, if there is no
default: label, it skips the block of code
altogether.
switch is a confusing statement to explain; its operation becomes much clearer with ...