Flow Control
Learn how to control the flow of a program using conditional statements.
We'll cover the following...
Previously we looked at how to compare statements, such as checking if two values are equal to each other. In this section, we’re going to control the flow of a program by running different blocks of code depending on whether a statement is true or false. This is a bit like reaching a fork in the road in a program, where we can decide which direction our code will go in. This will help to make our programs much more interesting, as they can start to have different results depending on what happens.
If statements
An if statement can be used to run a block of code only if a certain condition returns true. For example, say that you wanted to check if you’re tired. If you are tired, the plan is to go to sleep. This can be illustrated in the following diagram:
In pseudocode, this could be written as follows:
if you are tired then go to sleep.
In JavaScript, the code would look like this:
if (tired) {
sleep();
}
The code inside the block will only run if the condition in the parentheses is true. If the condition is not a Boolean value, it will be converted to a Boolean, depending on whether or not it’s truthy or falsy.
Let’s try writing some conditional code by writing the following in a console:
The alert box will only be displayed if energy < 3
evaluates to true
, so only if the value of the energy
variable is less than ...