Nested Decisions

Grade 4, page 6 of 11. A one-minute read.

You can put an if statement inside another if statement. This is called nesting:

JavaScript
const hasTicket = true;
const age = 10;

if (hasTicket) {
  if (age < 12) {
    console.log("Welcome! Here's your kids' popcorn. 🍿");
  } else {
    console.log("Welcome! Enjoy the movie.");
  }
} else {
  console.log("Sorry, you need a ticket first.");
}

It prints

Welcome! Here's your kids' popcorn. 🍿

Nesting works, but be careful. When you nest too deeply, your code starts looking like a staircase going sideways, and it becomes really hard to follow. Often you can flatten things out using && and else if:

JavaScript
const hasTicket = true;
const age = 10;

if (!hasTicket) {
  console.log("Sorry, you need a ticket first.");
} else if (age < 12) {
  console.log("Welcome! Here's your kids' popcorn. 🍿");
} else {
  console.log("Welcome! Enjoy the movie.");
}

It prints

Welcome! Here's your kids' popcorn. 🍿

Same result, much easier to read. A good rule of thumb: if you're nested more than two or three levels deep, there's probably a simpler way.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning