Page 100 - DCAP202_Fundamentals of Web Programming
P. 100
Unit 8: Programming Constructs in JavaScript
statement; Notes
break;
case caseLabel:
statement;
break;
default:
statement;
}
Notice the colons following the case and caseLabel keywords. This is absolutely required. Don’t
leave them out. Don’t substitute the colons with semi-colons, or your script won’t work. And
don’t forget the colon following the default keyword near the end of the script.
The switch statement begins with, of course, the switch keyword. Within the brackets following
the switch keyword is the expression, which is used to set the parameter that the rest of the script
will use as the data to be used to make a decision. Once this decision is made, the script looks for
a match among the various case keywords.
Each case keyword has a unique caseLabel associated with it. This is used to define each case
statement as a unique and individual entity to your script. Once a case with the matching
caseLabel is found, the statement within the case statement is executed.
On the end of the switch statement, you’ll see that a “default” keyword was used, with a statement
of its own given. This default statement is executed when none of the given cases match the
expression given in brackets following the switch keyword.
Notice also that break; statements were used. The break statements used in this way are required
to “break” out of the switch/case structure and go on to further actions. It is required so that the
rest of the case options below the selected case (as well as the default actions) aren’t executed.
Example: To further illustrate the concept, examine the following working example
which utilizes the switch/case statement.
var varOne = 100;
switch (varOne)
{
case 90:
document.write(“The value of varOne is 90”);
break;
case 100:
document.write(“The value of varOne is 100”);
break;
case 110:
document.write(“The value of varOne is 110”);
break;
default:
document.write(“The value of varOne is unknown”);
}
The example shows the declaration of a variable, varOne. varOne contains a number, which is
100. This varOne variable is then used as the expression of the switch statement. Now that the
script has the expression with to find a match, the several cases given are searched until a case is
found that matches the varOne value, which is 100. Since the second label matches the varOne
value given as the expression, the statement within that case statement is executed, which is a
document.write statement which writes the words “The value of varOne is 100” to the screen.
LOVELY PROFESSIONAL UNIVERSITY 93