JavaScript Nested Conditionals

1. Reference Guide

2. Key Vocab

Type Meaning Example Notes
conditional true/false if .... else.... determine what to print
boolean True/False boolean done = false; Used for conditions
char Single character char grade = 'A'; Always single quotes
string Text (sequence of chars) String name = "Paul"; Not primitive
array multiple values in one variable) numbers = [1, 2], [3, 4] Multiple values in one variable

3. Lesson Plan & Introduction

Imagine this: You’re deciding what to do on a Saturday afternoon.

First, you check whether you have tickets for a movie.

IF you have movie tickets:

  • You go to the theater, but then you need to check one more thing - did you bring snacks?
    • IF you brought snacks, you enjoy the movie with popcorn and a drink.
    • ELSE (if you have tickets but no snacks), you buy snacks at the theater.

ELSE (if you do not have movie tickets):

  • You plan an outdoor activity, BUT you still need to check the weather.
    • IF it is sunny, you go to the park.
    • ELSE, you stay home and play a board game.

See how you’re making decisions INSIDE other decisions? That’s a nested conditional!

Nested Conditional Code

Now let’s look at an example of nested conditional code using the weekend-plans analogy above.

// Decide what to do on Saturday afternoon
if (hasMovieTickets) {
    // First decision: We have tickets, so go to the theater
    goToTheater();

    // Nested decision INSIDE the movie-ticket condition
    if (hasSnacks) {
        console.log("Enjoying the movie with snacks");
    } else {
        buySnacks();
        console.log("Buying snacks at the theater");
    }

} else {
    // First decision: No tickets, so plan an outdoor activity

    // Nested decision INSIDE the no-tickets condition
    if (isSunny) {
        goToPark();
        console.log("Going to the park");
    } else {
        playBoardGame();
        console.log("Staying home to play a board game");
    }
}

In the code example above, there are 2 nested conditionals: there’s one in the if statement, and one in the else statement. If you have movie tickets, the snack check inside the if block will run. If you do not have movie tickets, we skip the if block entirely and go to the else statement, where a weather check will run.

Now you go ahead and try!

2. LxD Cycle Process

Empathize: Students are learning how a computer narrows down choices based on inputs.

Define:

  • POV: A conditional can contain another decision to make the program’s response more specific.
  • Learning Goal: Students will be able to implement a nested conditional inside an existing conditional and explain why nested conditionals are useful.

Ideate:

  • HMW Question: What is the difference between a nested conditional and a regular conditional?
  • Activity: Try the simple Code Runners and the NFL and Leap Year Popcorn Hacks.

3. CS111 Requirements

This lesson practices introductory programming control flow through selection. Students will:

  • Identify Boolean conditions and the code blocks controlled by them.
  • Trace the order in which an outer and an inner condition are evaluated.
  • Use a nested if...else to make a more specific decision.
  • Predict and verify program output for different input values.

These are foundational CS 111 programming skills: reading, tracing, and writing code that selects actions based on conditions.

4. Lesson Plan

Learning Objective: Use a nested conditional to make a second decision inside an outer if or else block.

Success Criteria: You can point out the outer and inner conditions, predict which block runs, and explain the output.

Tech Talk

A nested conditional is an if statement inside another conditional. JavaScript checks the outer condition first, then checks an inner condition only if it reaches that code block.

5. Code Runners and Practice

Run each example as-is, predict its output, and then change the listed values. Complete the Popcorn Hack under each example before moving on.

A. Movie Plans

The snack decision is only checked when there is a movie ticket.

Code Runner Challenge

Run the example, then change hasMovieTicket or hasSnacks.

View IPYNB Source
%%js
// CODE_RUNNER: Run the example, then change hasMovieTicket or hasSnacks.
const hasMovieTicket = true;
const hasSnacks = false;
if (hasMovieTicket) {
  console.log("You can go to the movie.");
  if (hasSnacks) {
    console.log("Enjoy the movie with snacks.");
  } else {
    console.log("Buy snacks at the theater.");
  }
} else {
  console.log("Choose another activity.");
}
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Practice: Popcorn Hack 1 — Movie Snacks

Complete the nested conditional so the program checks whether the moviegoer brought snacks. Run it with both values of hasSnacks.

Code Runner Challenge

Add a nested conditional that checks hasSnacks.

View IPYNB Source
%%js
// CODE_RUNNER: Add a nested conditional that checks hasSnacks.
const hasMovieTicket = true;
const hasSnacks = true;
if (hasMovieTicket) {
  // TODO: If hasSnacks is true, print "Enjoy the movie with snacks."
  // Otherwise, print "Buy snacks at the theater."
} else {
  console.log("Choose another activity.");
}
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Practice: Popcorn Hack 2 — Game Door

Add a nested conditional to check the player’s level only after checking that they have a key. Test the code with a player who has no key and a player who has a key.

Code Runner Challenge

Add a nested level check inside the hasKey condition.

View IPYNB Source
%%js
// CODE_RUNNER: Add a nested level check inside the hasKey condition.
const hasKey = true;
const playerLevel = 3;
if (hasKey) {
  // TODO: If playerLevel is at least 3, print "Door opened."
  // Otherwise, print "Reach level 3 first."
} else {
  console.log("Find a key first.");
}
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Practice: Popcorn Hack 3 — NFL Divisions

Let’s say you want to know which division a team from a conference belongs to. Add a nested conditional inside each conference block to print the team’s conference and division.

Code Runner Challenge

Add nested conditionals to identify each NFL team's division.

View IPYNB Source
%%js
// CODE_RUNNER: Add nested conditionals to identify each NFL team's division.
// The outer conditional is written for you. Add an inner conditional in each block.
const NFL_TEAMS = [
  { name: "Buffalo Bills", conference: "AFC", division: "East" },
  { name: "Baltimore Ravens", conference: "AFC", division: "North" },
  { name: "Houston Texans", conference: "AFC", division: "South" },
  { name: "Kansas City Chiefs", conference: "AFC", division: "West" },
  { name: "Detroit Lions", conference: "NFC", division: "North" },
  { name: "Atlanta Falcons", conference: "NFC", division: "South" },
  { name: "Dallas Cowboys", conference: "NFC", division: "East" },
  { name: "San Francisco 49ers", conference: "NFC", division: "West" }
];
for (const team of NFL_TEAMS) {
  if (team.conference === "AFC") {
    // TODO: Add a nested conditional for AFC North, South, East, or West.
  } else {
    // TODO: Add a nested conditional for NFC North, South, East, or West.
  }
}
// Expected output: Buffalo Bills are in the AFC East, followed by the other teams' divisions.
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Practice: Popcorn Hack 4 — Leap Year

Complete the nested conditional to report whether each positive year is a leap year. A year is a leap year when it is divisible by 4 and is not divisible by 100, unless it is also divisible by 400.

Code Runner Challenge

Add a nested conditional to identify leap years.

View IPYNB Source
%%js
// CODE_RUNNER: Add a nested conditional to identify leap years.
const YEARS_TO_TEST = [2024, 2023, 1900, 2000];
for (const year of YEARS_TO_TEST) {
  if (Number.isInteger(year) && year > 0) {
    // TODO: Add a nested conditional that checks the leap-year rules.
    // Expected: 2024 and 2000 leap years; 2023 and 1900 are not.
  } else {
    console.log("Please enter a positive whole number for the year.");
  }
}
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

6. Homework Hack

Make a nested conditional that does the following:

  1. Contains more than one nested conditional.
  2. Uses the numbers 1–50.
  3. Checks whether each number is divisible by 5.
  4. Submit a screenshot of this and the earlier Code Runners in the submission box at the bottom.

Code Runner Challenge

Make a nested conditional homework.

View IPYNB Source
%%js
// CODE_RUNNER: Make a nested conditional homework.
// Use a loop to check the numbers 1 through 50.
// Include more than one nested conditional and check divisibility by 5.
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Grading Plan

This assignment is worth 1 point total:

  • 0.2 points: Complete and test the Movie Snacks Popcorn Hack.
  • 0.2 points: Complete and test the Game Door Popcorn Hack.
  • 0.2 points: Add nested conditionals to the NFL Divisions Popcorn Hack.
  • 0.2 points: Add the nested leap-year check and test all four years.
  • 0.2 points: Complete the Homework Hack and submit screenshots of the working Code Runners.

7. References

MiraCosta College. CS 111: Introduction to Computer Science I. Course catalog

MDN Web Docs. Making decisions in your code — conditionals

Submit Assignment

This submits the code from this lesson's code runner(s) below as a Gist for automatic review. Save each runner with its 💾 button before submitting.

    Need to update a submission later? Open the submissions dashboard.