Menu
Coddy logo textTech

Nested If - Else

Part of the Fundamentals section of Coddy's JavaScript journey — lesson 26 of 77.

We can place if / else if / else statements inside other if statements. This is called nesting, and it lets us check conditions in steps.

Example:

let result;

if (age > 18) {
    if (has_license) {
        result = "You can drive";
    } else {
        result = "Get a license first";
    }
} else {
    result = "Too young to drive";
}

The inner if only runs when the outer if is true.

Nested structures can go as deep as needed:

if (condition1) {
    if (condition2) {
        if (condition3) {
            // All three conditions are true
        }
    }
}

Use nesting when a decision depends on another decision being true.

challenge icon

Challenge

Create a program that checks if someone can enter a swimming pool.

Rules:

  • Must be at least 10 years old
  • If they are under 13, they must have an adult with them

Print exactly these messages:

  • If too young:
    Sorry, you are too young
  • If under 13 and no adult:
    Sorry, you need an adult with you
  • If under 13 with adult:
    You can enter with adult supervision!
  • If 13 or older:
    You can enter by yourself!

Try it yourself

let age = parseInt(inp[0]); // Don't change this line
let has_adult = inp[1] === "true"; // Don't change this line

// Write your code below
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals