Lesson 4: Program Flow and Conditional Statements
Conditional Statements
In this section we will look at how we write a programme that changes its outcome or purpose depending on a certain condition being true or false.
If statements
If statements work by executing a certain block of code if a given condition evaluates to the Boolean value 'True'.
If statements are used very regularly in JavaScript and can add a lot of functionality to our code.
Example
The following example demonstrates how an if statement works:
let x = 14;
if (x > 10) {
console.log("X is greater than 10");
}
In the example, we set the value of x to 14 on line 1. On line 2, the programme checks if x is greater than 10 in the brackets of the if statement. As 14 is greater than 10 then condition evaluates to true, and the code inside the curly braces on line 3 is run. If x was less than 10, then the system would skip the code inside the curly braces and we would have no output.
Try It!
Example 2
let maximumParkingSpaces = 50;
let numberOfCars = 62
if (numberOfCars > maximumParkingSpaces) {
console.log("There are too many cars and not enough car park spaces");
}
if (numberOfCars < maximumParkingSpaces) {
console.log("There are enough car park spaces");
}
Example 3
let age = 18;
if (age >= 18) {
console.log('You can sign up.');
} else {
console.log('You must be at least 18 to sign up.');
}
Further Reading