JavaScript Statements - Switch Hitter
(Page 3 of 4 )
As you can see from the above example, using the If...Else If...Else statement can lead to some lengthy code. And we all know you are lazy. I mean, how many times does your mother tell you to pick up your socks for crying out loud? And that pizza you ordered last week is so old it's now a calzone.
A simpler way to work with blocks of If...Else statements is to use the Switch Statement, which analyses a variable, and then checks through the values of each case. If it finds a match, it will execute that block of code. If not it moves on to the next case.
<html>
<body>
<script type="text/javascript">
var job = “Computers”
switch (job)
{
case “Computers”:
document.write("<b>You must be fat.</b>")
break
case “Model”:
document.write("<b>You must be dumb. It's good that yer pretty.</b>")
break
case “Professional Arm Wrestler”:
document.write("<b>Over the Top should have won an Oscar.</b>")
break
default:
document.write("<b>I don't really care what you do.</b>")
}
</script>
</body>
</html>
In this code, the variable job is given the value “Computers”. Then the value of job is checked against each case. If there is a match, it will execute the block of code. As you can see above, the first case is a match, so it would print:
You must be fat.
If the value was “Model”, it would have skipped the first case and executed the Model case, in which case, it would have printed: You must be dumb. It's good that yer pretty. And again, if the value was Professional Arm Wrestler, it would have skipped the first two cases and executed on the third case, resulting in the print out: Over the Top should have won an Oscar.
And finally, if none of the case's criteria are met, the default case is executed. In this case it would have printed: I don't really care what you do.
As you can see, the above saves us some coding and is easier to read if we ever need to refer to it again.
You will also notice the Break function. This prevents the code from automatically executing the next case.
Next: How to Enter Special Characters >>
More JavaScript Articles
More By James Payne