Course contentsShow
← JavaScript
Lesson 364 of 2,72310. LoopsFree lesson

Break in nested loops: Only exits the innermost

Understand that break only exits the immediately enclosing loop, not outer loops in nested structures.

Break in Nested Loops: Only Exits the Innermost

You'll learn: How break behaves when you have loops inside loops — and why it doesn't exit everything at once.

The Core Idea

When you write a break statement inside nested loops (a loop within another loop), it only exits the innermost loop that contains it. The outer loop keeps running as if nothing happened. This can surprise beginners who expect break to stop all looping immediately.

Think of nested loops like boxes inside boxes. Using break is like climbing out of the smallest box you're currently in — but you're still inside all the larger boxes around it.

How It Works

for (let i = 1; i <= 3; i++) {
  console.log(`Outer loop: ${i}`);
  
  for (let j = 1; j <= 3; j++) {
    console.log(`  Inner loop: ${j}`);
    if (j === 2) {
      break; // Only exits the inner loop
    }
  }
}

// Output:
// Outer loop: 1
//   Inner loop: 1
//   Inner loop: 2
// Outer loop: 2
//   Inner loop: 1
//   Inner loop: 2
// Outer loop: 3
//   Inner loop: 1
//   Inner loop: 2

Notice how each time the inner loop hits break, it stops that inner loop, but the outer loop continues with its next iteration.

If you truly need to exit multiple loops at once, you'll need to use labeled statements (which you learned in earlier lessons) or set a flag variable that the outer loop checks.

Key Takeaway: break only exits the loop it's directly inside — nested outer loops continue running normally.