Java Reference
In-Depth Information
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.
Try It Out Using the switch Statement
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_examp3.htm.
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<body>
<script type=”text/javascript”>
var secretNumber = prompt(“Pick a number between 1 and 5:”, “”);
secretNumber = parseInt(secretNumber);
switch (secretNumber)
{
case 1:
document.write(“Too low!”);
break;
case 2:
document.write(“Too low!”);
break;
case 3:
document.write(“You guessed the secret number!”);
break;
case 4:
document.write(“Too high!”);
break;
case 5:
document.write(“Too high!”);
break;
default:
document.write(“You did not enter a number between 1 and 5.”);
break;
}
Search WWH ::




Custom Search