Nested Conditions

A block of code can contain any code, even another if statement. An if inside the block of another if is called a nested condition. It's useful when one question only makes sense after another. At the movies, for example, we first check whether the visitor has a ticket, and only then how old they are:

const hasTicket = true;
const age = 15;
if (hasTicket) {
    if (age >= 18) {
        console.log("Enjoy the movie");
    } else {
        console.log("Sorry, this movie is for adults only");
    }
} else {
    console.log("Please buy a ticket first");
}

This prints:

Sorry, this movie is for adults only

The inner if statement runs only when hasTicket is true. Each nested block is indented by 4 more spaces, so that you can see which } and which else belong to which if. Without indentation, nested conditions quickly get confusing.

Nested conditions can often be rewritten with logical operators and else if. This code does the same:

const hasTicket = true;
const age = 15;
if (hasTicket && age >= 18) {
    console.log("Enjoy the movie");
} else if (hasTicket) {
    console.log("Sorry, this movie is for adults only");
} else {
    console.log("Please buy a ticket first");
}

This prints:

Sorry, this movie is for adults only

The program gets to else if (hasTicket) only when the first condition is false. With a ticket, that means the visitor is under 18. Neither way is wrong: pick the one that's easier to read in your situation.

Instructions

A student passes the exam with 50 points or more, and with 75 or more passes with distinction. In the block of if (points >= 50), in place of the comment, write a nested if statement with the condition points >= 75 that prints Passed with distinction, and with an else branch that prints Passed.

Change points to 60 and run the program. It should print Passed.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

12/13

Next