Breaking From ForEach in JavaScript

Written by mayallo | Published 2023/07/10
Tech Story Tags: javascript | typescript | nodejs | javascript-development | mdn | javascript-tutorial | javascript-fundamentals | programming-tips

TLDRIn JavaScript,`forEach()` is a function that loops over an array of elements. It takes a callback as a parameter and applies it to every element in the array. There is no way to stop or break a*Ā `for each()`Ā loop other than by throwing an exception.via the TL;DR App

In JavaScript,Ā forEach()Ā is aĀ FUNCTIONĀ that loops over an array of elements. It takes a callback as a parameter and applies it to every element in the array.

I know that you landed on this page to know the direct way to break fromĀ forEach(), but I’m sorry to tell you thatĀ you can’t. AsĀ MDN:

There is no way to stop or break aĀ forEach()Ā loop other than by throwing an exception. If you need such behavior, theĀ forEach()Ā method is the wrong tool.

Having said that, you shouldn’t useĀ forEach()Ā if you know previously that you might need to break from the loop. Instead, you should useĀ for...of,Ā that’s the perfect solution.

However, for just the sake of learning, let’s introduce some workarounds.

First of all, let’s consider the following example as a basis:

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

arr.forEach(num => {
  doubled.push(num * 2);
});

console.log(doubled); // [ 2, 4, 6, 8 ]

Consider the case, you want to break if the element wasĀ 3.

Using For…Of Instead

As I said, that’s the recommended solution as you can break from the loop easily using theĀ breakĀ keyword.

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

for (const num of arr) {
  if (num === 3) break;
  doubled.push(num * 2);
}

console.log(doubled); // [ 2, 4 ]

Using Every() Or Some() Instead

In JavaScript,Ā every()Ā andĀ some()Ā are two functions likeĀ forEach(), the difference is that:

  • every(): Returns true ifĀ everyĀ callback returns true.
  • some(): Returns true if one callbackĀ at leastĀ returns true.

Fortunately, we can use these facts to break the loop as follows:

  • every(): You should returnĀ falseĀ at the element you want to break out.
  • some(): You should returnĀ trueĀ at the element you want to break out.

Firstly, let’s useĀ every():

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

arr.every(num => {
  if (num === 3) return false;
  doubled.push(num * 2);
  return true;
})

console.log(doubled); // [ 2, 4 ]

Secondly, let’s useĀ some():

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

arr.some(num => {
  if (num === 3) return true;
  doubled.push(num * 2);
  return false;
})

console.log(doubled); // [ 2, 4 ]

Using A Variable Helper

In this workaround, you retain using theĀ forEach()Ā function. In addition, you use a variable that controls the flow.

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

let shouldBreak = false; // Variable helper

arr.forEach(num => {
  if (num === 3) shouldBreak = true;
  if (shouldBreak === false) doubled.push(num * 2);
})

console.log(doubled); // [ 2, 4 ]

Conclusion

In this article, we knew that there is no direct way to break from theĀ forEach()Ā function.

Then, we knew that it is preferable to useĀ for...ofĀ instead to loop over an array of elements.

Finally, we introduced some workarounds that you can use to break from the forEach()Ā function, like using other functions likeĀ every()Ā orĀ some(), or by using a variable helper that controls the flow.

Also published here.

If you found this article useful, check out this article as well:

Thanks a lot for staying with me up till this point. I hope you enjoy reading this article.


Written by mayallo | Feel free to contact me at https://mayallo.com/contact/
Published by HackerNoon on 2023/07/10