JavaScript ForEach Break Example

JavaScript ForEach Break Example | Here are a few techniques we can use to break a forEach() loop, which almost seems impossible. The forEach() method in JavaScript runs a function on each element of an array. However, employing the break statement is a syntax error because forEach() is a function rather than a loop:-

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

To iterate through an array, we advise using for/of loops unless there is a compelling reason not to. Here are some ways though, if you’re stuck with a forEach() that needs to stop after a specific point and refactoring to use for/of is not an option:-

1. Switch to every() from forEach()

When the callback function returns a false value, the every() function halts iterating through the array in the same way that forEach() does.

[1, 2, 3, 4].every((v) => {
  if (v > 2) {
    return false;
  }

  console.log(v);
  // Make sure you return true.
  // If you don't return a value,
  // `every()` will stop after 1st iteration.
  return true;
});

Output:-

1
2

Returning false from every() result in a break, while returning true results in a continue.

Use the find() function instead, which is similar but only flips the boolean values. Returning true from find() results in a break, while returning false results in a continuation.

2. Eliminate the Values You Want to Ignore

Consider how to filter out all the values you don’t want forEach() to iterate over instead of how to escape a forEach() loop. This strategy adheres more to the fundamentals of functional programming.

The callback is required when using the findIndex() function, which then returns the first index of the array whose value the callback returns truthy for. The slice() function then duplicates a portion of the array.

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

// Instead of trying to `break`, 
// slice out the part of the array 
// that `break` would ignore.
arr.slice(0, arr.findIndex(v => v > 2)).forEach(v => {
  console.log(v);
});

Output:-

1
2

Also see:- JavaScript ForEach Continue Example

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *