Course contentsShow
← JavaScript
Lesson 314 of 2,7239. Control FlowFree lesson

Nested If Statements

Learn to nest if statements inside each other and when this pattern is appropriate versus alternatives.

Nested If Statements

You'll learn how to place if statements inside other if statements and when this pattern makes sense.

What Are Nested If Statements?

A nested if statement is simply an if statement placed inside another if statement's block. This lets you check additional conditions only when an outer condition is already true.

Think of it like a series of security checkpoints: you only reach the second checkpoint if you pass the first one.

Basic Syntax

if (outerCondition) {
  // This runs if outerCondition is true
  
  if (innerCondition) {
    // This runs if BOTH outerCondition AND innerCondition are true
  }
}

Practical Example

let age = 20;
let hasTicket = true;

if (age >= 18) {
  // First check: Is the person an adult?
  
  if (hasTicket) {
    // Second check (only reached if adult): Do they have a ticket?
    console.log("Welcome to the concert!");
  }
}

The inner if (hasTicket) only runs when age >= 18 is true.

When to Use Nesting

Nesting is appropriate when:

  • One condition only matters if another is true first
  • You want to avoid checking unnecessary conditions

However, you can often rewrite nested ifs using the && operator:

// These are equivalent:
if (age >= 18 && hasTicket) {
  console.log("Welcome!");
}

Use && when both conditions are equally important checks. Use nesting when the logic truly has layers or when you need different actions at each level.

Key Takeaway: Nested if statements check conditions within conditions, but avoid deep nesting—use && or else if for clearer, more readable code when possible.