Better Decision-making with If...Else Statements

In the previous section, we learned how to use the If statement in Sonar (read it here, if you skipped that, or if you need a refresher).

In this section, we will build on our knowledge of If statements to make our programs make more complex decisions using the If...Else statement.

Sometimes, we make sentences that resemble:

  • "if it rains today, I will not go out; but if it doesn't, I will"

  • "if today is a weekday, I will have to go to school; but if it isn't, I will go out to play"

  • "if I click the Netflix icon, my iPhone will start the Netflix app; but if I click the TikTok icon, my iPhone will start the TikTok app"

Each of these sentences have two conditions that are related. The two conditions are "opposites" (i.e they cannot be true at the same time).

  • it cannot rain and not rain at the same time

  • it cannot be a weekday and the weekend at the same time

  • you cannot click the Netflix app and the TikTok app at the same time (well, you can try –– but you can't; trust me, I tried)

Each of these sentences look like this:

Drawing

For example:

Drawing

Examples with If-Else

Many countries have a legal drinking age of 18 years. We can write a program that checks whether a person is able to drink alcohol or not.

let adult_age = 18
let age = 17

if (age < adult_age) {
    print("You are not an adult")
} else {
    print("Here. Have a beer.")
}

// outputs You are not an adult

If we change age to a number greater than or equal to 18, the person will be allowed to drink:

let adult_age = 18
let age = 18 // any number from 18 upwards

if (age < adult_age) {
    print("You are not an adult")
} else {
    print("Here. Have a beer.")
}

// outputs Here. Have a beer.

An Improved Traffic Controller with If-Else

We can make our traffic controller better by replacing our If statements with If-else:

let traffic_condition = "ready"

if (traffic_condition == "stop") {
    print("red")
} else {
    if (traffic_condition == "ready") {
        print("amber")
    } else {
        if (traffic_condition == "go") {
        print("green")
    }
}

Take a minute to think about our improved program to be certain you understand it.

Last updated