DEV Community

MR POA
MR POA

Posted on

Let’s talk a bit about forEach and its relation to break, continue, and return

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
  }
});
Enter fullscreen mode Exit fullscreen mode

❌ 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);
});
Enter fullscreen mode Exit fullscreen mode

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);
});
Enter fullscreen mode Exit fullscreen mode

array.every()
Stops when the callback returns false:

alphabets.every((alphabet) => {
  if (alphabet === "D") return false;
  console.log(alphabet);
  return true;
});
Enter fullscreen mode Exit fullscreen mode

✅ Rule of thumb
If you need to stop a loop, don’t use forEach.

Top comments (0)