In our last tutorial we covered where to place JavaScript code, how to work with variables, and print stupid things to the screen. In this installment we will be working with Conditional Statements, Switch Statements, and if there is time, Operators. So call up your date and cancel (who am I kidding? You'd rather go on a date than study this) and let's get to work.
We've all been given conditions before, especially if you've ever been mugged. If you give me all your money I won't beat you up. If you give me all your money, then I will beat you up. Give me your money and I won't beat you up, or else I will beat you up and take your money. Those are all good examples of conditional statements. They simply state "do this and this happens."
There are four types of Statements in JavaScript. They are the If Statement, the If...Else statement, the If...Else If...Else Statement, and the Switch Statement.
What If
What if I weren't a fat nerd? What if I had a name like Beauregard Iffington the Third and owned a big fat yacht? What if Gary Coleman wrestled an alligator? Would it still be hungry afterwards?
Okay that isn't how an If Statement works. It's just some questions that have been plaguing me lately. An If Statement says if this condition is true, do this. Here is how that looks in code:
<html>
<body>
<script type="text/javascript">
var job = “Computers”
if (job == “Computers”)
{
document.write("<b>You must be fat.</b>")
}
</script>
</body>
</html>
In the above example, we assigned the value Computers to a variable we named job. We then made an if statement that stated if the value of jobs is Computers, print something out. Since the value of jobs does match the criteria of our if statement, the following would print out to the screen:
You must be fat.
If the value of job had been anything else, nothing would have happened.