Consider the following example:
const alphabets = ["A","B","C","D","E","F"];
alphabets.forEach((alphabet) => {
if (alphabet === "D") {
break; // ❌ SyntaxError: Illegal break statement
continue; // ❌ SyntaxError: no surrounding iteration statement
}
});
❌ This results in an error because forEach is not a loop statement.
It is a built-in array method that accepts a callback function.
The keywords break and continue only work inside real loop statements such as:
for
for...in
for...of
while
What about return?
Using return inside forEach only exits the callback function, not the loop itself.
The iteration continues normally.
Example:
const alphabets = ["A","B","C","D","E","F"];
alphabets.forEach((alphabet) => {
if (alphabet === "D") {
return; // exits only the callback
}
console.log(alphabet);
});
Output:
A
B
C
E
F
⚠️ Note:
Using return false here behaves exactly the same as return.
forEach does not care about the returned value.
Summary
forEach
❌ is not a loop statement
❌ does not support break or continue
✔️ return only exits the callback function
To use break or continue, you must use real loops:
for
for...in
for...of
while
Alternatives to forEach when you need to stop iteration
array.some()
Stops when the callback returns true:
alphabets.some((alphabet) => {
if (alphabet === "D") return true;
console.log(alphabet);
});
array.every()
Stops when the callback returns false:
alphabets.every((alphabet) => {
if (alphabet === "D") return false;
console.log(alphabet);
return true;
});
✅ Rule of thumb
If you need to stop a loop, don’t use forEach.

Top comments (0)