JavaScript Statements - If...Else
(Page 2 of 4 )
Now let's say we wanted something to happen if the value of our variable job had been different. In that case we would use an If...Else statement, which basically says: If this is true, do that, else do something else. I bet you want to see that in code. Then put on your glasses and take a gander.
<html>
<body>
<script type="text/javascript">
var job = “Computers”
if (job == “Computers”)
{
document.write("<b>You must be fat.</b>")
}
else
{
document.write("<b>You must not be fat</b>")
}
</script>
</body>
</html>
Look at that masterful coding. You can only hope to be a coding wizard like me some day. The above code extends our previous sample. If the value of jobs is Computers, it will still print the line: You must be fat. However, if the value of jobs is anything else, it will print: You must not be fat.
If...Else If...Else
Let's say we wanted to insult people that worked in several different fields. We can do that as well; all we need is our friend the If...Else If....Else Statement.
<html>
<body>
<script type="text/javascript">
var job = “Computers”
if (job == “Computers”)
{
document.write("<b>You must be fat.</b>")
}
else if (job == “Model” || job == “Supermodel”)
{
document.write("<b>You must be dumb. It's good that yer pretty.</b>")
}
else
{
document.write("<b>That sounds boring.</b>")
}
</script>
</body>
</html>
Once again we have modified our original If statement. If the value of job is equal to “Computers” (which it is), it still prints the line: You must be fat. This time however, we also ask if the value of job is Model OR Supermodel. It isn't, but if it was either value, then the following would be printed to your screen: You must be dumb. It's good that yer pretty. And lastly, if the value was anything else, this would have printed: That sounds boring.
Just to clarify, you can add as many else if statements as you want, and insult all the jobs you can imagine. It's a great way to kill an hour or two on a Friday.
Next: Switch Hitter >>
More JavaScript Articles
More By James Payne