break foreach loop javascript

How to Break ForEach Loop in JavaScript

JavaScript provides multiple ways to loop through our data. You can use while or for loop, or you may also use forEach loop. The ForEach loop is available for all JS arrays and allows you to call a function for each element of the array. But sometimes while using ForEach loop, you may want to stop or exit from the loop. In this article, we will learn how to break forEach loop in JavaScript.


How to Break ForEach Loop in JavaScript

Let us say you have the following array in JavaScript.

var nums = [1,2,3,4,5];

Let us say we use these numbers as shown below.

var sum=0;
nums.forEach(add_num);

function add_num(n){
 sum+=n;
}

Let us say you want to break out of the forEach loop when the current element is 3.

One of the ways to do this is to throw an exception when your current item is 3.

var BreakException = {};

try {
  [1, 2, 3, 4, 5].forEach(function(el) {
    console.log(el);
    if (el === 3) {throw BreakException}
    else{add_num(el);}
  });
} catch (e) {
  if (e !== BreakException) throw e;
}

In the above code, the forEach statement loops through the array one item at a time. When the current item is 3, it throws an exception.

As you can see, it is not a good practice to throw an exception deliberately in your code. So it is advisable to use traditional for loop with break statement for this purpose. In the following code, we simply issue a break statement when the current element is 3.

var arr = [1, 2, 3, 4, 5];
for (let i = 0; i < 6; i++) {
  if (arr[i] === 3) { break; }

  else{add_num(arr[i]);}
  text += "The number is " + i + "<br>";
}

Alternatively, you can also use some() function available for each JS array. It allows you to check if at least one element of the array matches a given condition, using a callback function, and returns true if there is at least element that returns true for the callback function. Otherwise it returns false.

[1, 2, 3, 4, 5].some(function(el) {
  console.log(el);
  return el === 3;
});

In this article, we have learnt a couple of ways to break foreach loop in JavaScript. But they both involve using another way of execution – traditional for loop or some() function. As mentioned earlier, it is not a good way to deliberately throw exception to stop execution in forEach loop. So it is advisable to simply use the traditional for loop with break statement.

Also read:

How to Validate Decimal Number in JavaScript
How to Fix Uncaught ReferenceError in jQuery
How to Detect Browser in JavaScript
How to Get Array Intersection in JavaScript
How to Sort Object Array By Date Keys

Leave a Reply

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