23.04.2013 Views

javascript

javascript

javascript

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 4 ■ CONTROLLING FLOW<br />

114<br />

break;<br />

case 83:<br />

name = "Miller";<br />

break;<br />

case 86:<br />

name = "Ward";<br />

break;<br />

case 92:<br />

case 97:<br />

name = "Harrison";<br />

break;<br />

case 94:<br />

name = "Timmons";<br />

break;<br />

case 96:<br />

name = "Hood";<br />

default:<br />

name = "not worn by any Steeler";<br />

break;<br />

}<br />

"Number " + jersey + " is " + name + ".";<br />

// "Number 96 is not worn by any Steeler."<br />

As you can see, JavaScript will continue running statements, even those in the default clause, until<br />

it either encounters a disruptive statement or encounters the closing curly brace. By neglecting to put a<br />

break statement after the case clause for 96, we effectively had JavaScript run the following if condition:<br />

if (jersey === 96) {<br />

name = "Hood";<br />

name = "not worn by any Steeler";<br />

}<br />

Note that had we put the default case at the top of the switch, JavaScript would not have fallen<br />

through from the case clause for 96 to the default.<br />

As previously noted, if a switch appears within a function, then you can end paths with a return<br />

disruptive statement instead of a break. Oftentimes, the return statement not only marks the end of the<br />

path but also is the path itself. So, let’s go ahead and put our switch in a function so that we can use<br />

return statements:<br />

var jersey = 7, name = "";<br />

function identifyPlayer() {<br />

switch (jersey) {<br />

case 7:<br />

return "Roethlisberger";<br />

case 10:<br />

return "Holmes";<br />

case 17:<br />

return "Wallace";<br />

case 34:<br />

return "Mendenhall";<br />

case 43:<br />

return "Polamalu";<br />

case 83:<br />

return "Miller";<br />

case 86:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!