Menu
Coddy logo textTech

Nested If - Else

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

We can nest if-else if-else statements within each other. This allows us to create hierarchical decision-making structures.

For 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";
}

It can be infinite nested:

if (condition1) {
	// if condition1 is true
	if (condition2) {
		// if condition1 and condition2 are true
		if (condition3) {
		    // if condition1, condition2 and condition3 are 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!

Cheat sheet

You can nest if / else statements to make step-by-step (hierarchical) decisions:

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

Nesting means putting one condition inside another:

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

Use nesting when each check depends on the previous one being true.

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