JavaScript by Patrik

JavaScript's forEach() function executes a function on every element in an array. However, since forEach() is a function rather than a loop, using the break statement is a syntax error:

[1, 2, 3, 4, 5].forEach(v => {
  if (v > 3) {
    // SyntaxError: Illegal break statement
    break;
  }
});

We recommend using for/of loops to iterate through an array unless you have a good reason not to. However, if you find yourself stuck with a forEach() that needs to stop after a certain point and refactoring to use for/of is not an option, here are four workarounds.

Comments

Leave a Comment

All fields are required. Your email address will not be published.