Using Switch Case Statements


Advanced

Switch case statements are used to control multiple execution branching using the value of a single variable. Multiple if statements could achieve the same results as a switch statement, but the syntax would be complex and confusing. Put another way, a single switch statement can replace a whole bunch of if statements—and make for greater clarity of code.

Do It Right!

Switch statements work by telling the computer to conditionally execute blocks of code depending on the value, or case, of a variable.

It’s probably easiest to understand switch statements when you see them in action, so let’s start with a simple switch statement and then follow it up by rewriting part of the Rock, Scissors, and Paper game using switch rather than if statements—because the game is so much fun!

Seeing a Simple Switch Example in Action

Listing 3-9 shows an example of a simple switch statement that branches depending upon the value of the variable n. Figure 3-10 shows the results of the program.

Listing 3.9: A Simple Switch Statement Demonstration

start example
 var n = 1;  switch (n) {  case 1:     {       document.write("n equals 1");       break;     }  case 2:     {      document.write("n equals 2");      break;            }      case 3:     {       document.write("n equals 3");       break;     }  default:     {       document.write("No match!");       break;     }  } 
end example

click to expand
Figure 3-10: This simple demonstration shows how switch statements work.

Note the use of break statements at the end of each execution block. These cause JavaScript to exit the switch statement. If they were omitted, execution would proceed to the next branch of the switch statement rather than terminating the switch after one block was executed.

Rewriting Rock, Scissors, and Paper

Listing 3-7 shows the original whoWon function in the Rock, Scissors, and Paper program. If you look at the code, you can see that it’s organized around four top-level if statements that test for the value of the variable iplay —the play randomly selected by and for the computer. These if statements, in the order shown, use conditionals to check for the following values of iplay (see Table 3-2).

Table 3-2: iplay Values and Conditionals

Value

Conditional Expression

uplay

if (iplay == uplay) Note: If this is true, the game is tied.

"rock"

if (iplay == "rock")

"scissors"

if (iplay == "scissors")

"paper"

if (iplay == "paper")

The top-level conditional expressions shown in Table 3-2 create the structure of the whoWon function. If control passes via any but the first conditional, other if statements are still required to determine the winner.

In fact, the whoWon function could be diagrammed as shown in Figure 3-11.

click to expand
Figure 3-11: Flow chart of the whoWon function

Note

By convention, a diamond shape is used in flow charts to represent conditionals.

Advanced

The cool thing we can now do is replace the four conditionals shown in Listing 3-7 and Table 3-2 with a single switch case statement. Listing 3-10 shows how to do this.

Way Cool

Listing 3.10: The whoWon Function with Top-Level If Statements Replaced by a Single Switch Case Statement

start example
 function whoWon (iplay, uplay) {     // "I" am the computer     switch (iplay) {        case uplay:            return "IT'S A TIE! TRY AGAIN, FRAIL HUMAN ENTITY?";        case "rock": {            if (uplay == "scissors")               return "I WIN! ROCK SMASHES SCISSORS! COMPUTERS FOREVER!"            else  return "YOU WIN. Paper covers rock. Paltry human, how did you beat me?";        }        case "scissors": {            if (uplay == "paper")               return "I WIN! SCISSORS CUT PAPER! CHIPS BEAT BRAINS!"            else  return "YOU WIN. Rock smashes scissors. Frail human, would you like to iconid=parrow     try again?";        }        case "paper": {            if (uplay == "rock")                 return "I WIN! PAPER COVERS ROCK! ROCK AND ROLL, BABY!"            else  return "YOU WIN. Scissors cut paper. Oh, vain flesh and bone entity, iconid=parrow    I'll get you   next time!";       }    }  } 
end example

So this is pretty neat, and it makes for much more readable code, always a good thing. Because it’s a good idea to try new code after you’ve written it and because Rock, Scissors, and Paper is so much fun, let’s play a round! Naturally, the computer wins (see Figure 3-12). I think maybe it’s cheating with that random number generator.

Advanced

click to expand
Figure 3-12: The computer wins again.

start sidebar
Using Break Statements and Return Statements

You may have noticed that when I showed you the general form of the switch case statement (see Listing 3-9), I said that a break statement had to be used with each case. Otherwise, program control simply continues to the next case, which is not generally what you want to happen. Why didn’t I use break statements in the switch case statement shown in Listing 3-10?

The answer is that each of the cases within the statement ends with a return statement. When JavaScript hits a return statement within a function, processing returns to the place that called the function originally. So, these return statements serve the same purpose as a break statement (while also returning a value, namely the string to be displayed).

You’ll learn much more about functions in Chapter 5, “ Understanding Functions.”

end sidebar




Learn How to Program Using Any Web Browser
Learn How to Program Using Any Web Browser
ISBN: 1590591135
EAN: 2147483647
Year: 2006
Pages: 115
Authors: Harold Davis

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