Creating switch Statements

Creating switch Statements

The JavaScript switch statement is the next step up in decision making after the if statement. You use the switch statement if you want to test a large number of cases and don't want to construct a long ladder of if...else statements.

Here's how it works: You compare a test expression against a number of values. If one of those values matches, the code associated with the value is executed until the JavaScript interpreter finds a break statement. Here's what the switch statement looks like in outline:

 switch(  test  ){     case  value1:  .           .           .  code executed if test matches value1  .           .           .         break;     case  value2:  .           .           .  code executed if test matches value2  .           .           .         break;     case  value3:  .           .           .  code executed if test matches value3  .           .           .         break;     default:           .           .           .  code executed if test doesn't matches any case  .           .           .         break; } 

Here, you list the possible values to match against with the case statement. When a value given in a case statement matches, the corresponding code (that is, the code that follows the case statement up to a break statement) is executed.

You might also note that I've added a default statement to the end of the list of case statements. If no case statement's values have matched the text expression, the code in the default statement is executed, in case you want to make sure some code is executed. The default statement is optional.

Here's an example putting the switch statement to work. In this case, I'm checking user input, which I've stored in a variable named userInput , against various test strings, and displaying messages to match the various possibilities:

 switch(userInput){     case "EDIT":         document.writeln("Now entering EDIT mode.")         break;     case "HELP":         //This response should look familiar to users...         document.writeln("Sorry, no help is available.")         break;     case "QUIT":         document.writeln("Are you sure you want to quit?")         break;     default:         document.writeln("I do not understand that response.")         break; } 


Real World XML
Real World XML (2nd Edition)
ISBN: 0735712867
EAN: 2147483647
Year: 2005
Pages: 440
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net