Conditionals are a way to let computers make decisions for you. A real world example would be you arrive at a fork in the road. You can either go left (A) or go right (B). You could write a program and when you want to go left, you write code that tells the computer to go (A). And when you want to go right, you write code that tells the computer to go (B). But that means you're constantly having to write code and issue commands to the computer. Wouldn't it be nice if you could write code once that says "if I want to go left, go (A) otherwise I want to go right go (B)". Luckily, this is exactly what conditional statements do for you. Let's look at the basic structure:
ifstarts the conditional statement.
foorepresents the condition we're testing against. In the previous example, this would be whether we want to go left or right. But for code, it would have to something that we could evaluate to either be
not true. More on this in a little bit. And notice that the
// do Xand
// do Yare on separate lines, this is the code you want the computer to execute if the preceding condition is true. And lastly, there is an
elsethat is the catch-all if none of the previous conditions are true. In our example, there is only one condition
foobut we can actually have more conditions. Let's look at a more complex scenario:
And now we have multiple conditions using
else if. It should be noted that only a single condition or the
elseblock will execute. That's because the computer will test each condition in the order specified. So for our example, the computer will test
baz. And if none of those are true, then it will go to
elseand execute whatever code is specified - in our case
// do Z.
Next, let's talk about defining the conditional (e.g.
baz). The structure of a conditional is something that can evaluate to
false. The most common way of doing this is to specify whether two things are equal or not equal and in the case of numbers they could also be greater than or less than. Here is how each of those would look:
And what if you have two variables that you want to check at the same time. For example, what if you had variables
michiand you wanted to check the value for both. If you wanted to test if
mochiwas equal to
michiwas equal to
1, it would look like:
So to test that both conditions evaluate to
true, we use the
&&operator. And you can use the
&&operator to string as many things as you want. So for example if you want to check
momo, it would look like
(mochi === 0 && michi === 1 && momo === 2).