Java Reference
In-Depth Information
The best way to think of the switch statement is “Switch to the code where the case matches.” The
switch statement has four important elements:
The test expression
The case statements
The break statements
The default statement
The test expression is given in the parentheses following the switch keyword. In the previous
example, you are testing using the variable myName . Inside the parentheses, however, you could have
any valid expression.
Next come the case statements. The case statements do the condition checking. To indicate
which case statements belong to your switch statement, you must put them inside the curly braces
following the test expression. Each case statement specifies a value, for example "Paul" . The case
statement then acts like if (myName == "Paul") . If the variable myName did contain the value
"Paul" , execution would commence from the code starting below the case "Paul" statement and
would continue to the end of the switch statement. This example has only two case statements, but
you can have as many as you like.
In most cases, you want only the block of code directly underneath the relevant case
statement to execute, not all the code below the relevant case statement, including any other
case statements. To achieve this, you put a break statement at the end of the code that
you want executed. This tells JavaScript to stop executing at that point and leave the switch
statement.
Finally, you have the default case, which (as the name suggests) is the code that will execute when
none of the other case statements match. The default statement is optional; if you have no default
code that you want to execute, you can leave it out, but remember that in this case no code will
execute if no case statements match. It is a good idea to include a default case, unless you are
absolutely sure that you have all your options covered.
Using the switch Statement
trY it out
Let's take a look at the switch statement in action. The following example illustrates a simple guessing
game. Type the code and save it as ch3 _ example3.html .
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 3, Example 3</title>
</head>
<body>
<script>
var secretNumber = prompt("Pick a number between 1 and 5:", "");
secretNumber = parseInt(secretNumber, 10);
switch (secretNumber) {
Search WWH ::




Custom Search