# Conditionals

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:

Copy code

So the if starts the conditional statement. foo represents 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 true or not true. More on this in a little bit. And notice that the // do X and // do Y are on separate lines, this is the code you want the computer to execute if the preceding condition is true. And lastly, there is an else that is the catch-all if none of the previous conditions are true. In our example, there is only one condition foo but we can actually have more conditions. Let's look at a more complex scenario:

Copy code

And now we have multiple conditions using else if. It should be noted that only a single condition or the else block will execute. That's because the computer will test each condition in the order specified. So for our example, the computer will test foo then bar and then baz. And if none of those are true, then it will go to else and execute whatever code is specified - in our case // do Z.

Next, let's talk about defining the conditional (e.g. foo or bar or baz). The structure of a conditional is something that can evaluate to true or 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:

Copy code

And what if you have two variables that you want to check at the same time. For example, what if you had variables mochi and michi and you wanted to check the value for both. If you wanted to test if mochi was equal to 0 and michi was equal to 1, it would look like:

Copy code

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 mochi, michi and momo, it would look like (mochi === 0 && michi === 1 && momo === 2).

Next: Loops

Join our community

Your sign-up could not be saved. Please try again.
Your sign-up was successful.

Sign-up for our newsletter and continue your journey to becoming a software engineer.