The switch/case Structure
By Stephen Bucaro
The switch/case structure lets you match a variable's or expression's
value to a number of values and then execute code when a match is found. A
description of the switch/case structure is shown below.
switch(expression)
{
case (value):
statements;
break;
case (value):
statements;
break;
default:
statements;
}
The variable or expression is placed in brackets after the switch
statement. The body of the structure contains one or more comparison values in
brackets case statements. Each case section defines a block of
code to be executed if its value matches the value in the switch statement.
Note that the last line of each case branch (except the last one) is the
break command. If you omit the break command, the code in every case
section following the one with the matching value will be executed until a break
command is found. The break command causes execution to break out of the
switch/case structure.
• The omission of the break command might be an error, but sometimes it is used
as a deliberate method of program flow control.
Note the default branch at the end of the structure. Use the default
section for code to execute if none of the case values are found to match.
The example below shows a switch/case structure which branches based upon
matching the value of a variable placed in the switch statement.
switch(a)
{
case(1):
alert("a = 1");
break;
case(2):
alert("a = 2");
break;
case(3):
alert("a = 3");
}
|