Course contentsShow
← JavaScript
Lesson 848 of 2,72320. Array Iteration and TransformationFree lesson

forEach Cannot Break

Why forEach doesn't support break or continue, and alternatives for early exit scenarios.

forEach Cannot Break

You'll learn why forEach doesn't allow early exit and what to use instead when you need to stop mid-iteration.

The Limitation

Unlike traditional for loops, the forEach method cannot be stopped early. You cannot use break or continue inside forEach—attempting to do so will throw a syntax error. This is because forEach is a method that takes a callback function, and break/continue only work with loop statements, not functions.

const numbers = [1, 2, 3, 4, 5];

// This THROWS AN ERROR:
numbers.forEach(num => {
  if (num === 3) {
    break; // ❌ SyntaxError: Illegal break statement
  }
  console.log(num);
});

Why This Matters

Think of forEach like a tour guide who insists on showing you every single attraction—you can't say "I'm done, let's leave now." The guide visits every stop no matter what.

The Alternative

If you need to exit early (like when you've found what you're searching for), use a regular for loop instead:

const numbers = [1, 2, 3, 4, 5];

for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] === 3) {
    break; // ✅ Works fine
  }
  console.log(numbers[i]); // Logs: 1, 2
}

Key Takeaway: forEach always visits every element—if you need early exit capabilities with break or continue, stick with traditional for loops or for...of loops instead.