How to stop forEach() method in JavaScript?


In JavaScript, Programmers can use the forEach() method to iterate through the array of elements. We can call a callback function, which we can pass as a parameter of the forEach() method for every array element.

Sometimes, we may require to stop the forEach() loop after executing the callback function for some elements. We can use the ‘break’ keyword with a normal loop to stop it, as shown below.

for(let i = 0; i < length; i++){
   // code
   if( some condition ){
      break;
   }
}

But we can’t use the ‘break’ keyword with the forEach() method.

array.forEach(element => {
   // code
   if( some condition ){
      break;
   }
});

The above code will not stop the execution of the forEach() loop.

This tutorial will teach various approaches to stop forEach() loop in JavaScript.

Use the return keyword

The return keyword stops the execution of the code. In the forEach() loop, it works as a continue statement.

Syntax

Users can follow the syntax below to use the return keyword to stop the execution of the forEach() method.

array.forEach(function (element, index) {
   if (condition) {
      return; 
   }
});

In the above syntax, if the condition becomes true, it will not execute the code of the callback function for the element.

Example 1

In the example below, We are using the forEach() method with the array of strings. We call the callback function for every element, which prints every element. We used the condition that if index > 2, it returns from the callback function. So it will not print the element.

<html>
<body>
   <h2>Using the <i>return keyword</i> to stop the execution of the forEach() loop.</h2>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById('output');
      let array = ["string1", "string2", 10, 20, false, true];
      function callback(element, index) {
         // stop execution of for-loop
         if (index > 2) {
            return; // works like a continue statement
         }
         output.innerHTML += "The array element is " + element + "<br/>";
      }
      array.forEach(callback);
   </script>
</body>
</html>

The ‘return’ keyword doesn’t break the forEach() method, but it works as a continuous keyword if the condition becomes true.

Stop the forEach() loop by throwing the exception

Another way to stop the execution of the forEach() loop is using the try-catch statement. We can throw the error when we want to stop the execution of the forEach() method. Also, we can catch the error in the 'catch' block. We can execute whatever code we need to execute after the forEach() method in the ‘finally’ block.

Syntax

Users can follow the syntax below to stop the forEach() method using the try-catch statement.

try {
   array.forEach((ele) => {
      if (condition) {
         throw new Error("Break the loop.")
      }
   })
} catch (error) {
}

In the above syntax, we have used the throw keyword to throw the exception and break the forEach() method.

Example 2

In the example below, we have used the forEach() method with the try-catch statement. In the callback function of the forEach() method, we check the element type, and if we find any element with the “number” type, we throw the error.

So, it will stop the execution of the forEach() method.

<html>
<body>
   <h2>Using the <i>try-catch statement</i> to stop the execution of the forEach() loop.</h2>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById('output');
      let array = ["Cpp", "c", "Java", "JavaScript", 06, true, 43, false];
      try {
         array.forEach((ele) => {
            if (typeof ele == "number") {
               throw new Error("Break the loop.")
            }
            output.innerHTML += "Element value is " + ele + "<br/>";
         })
      } catch (error) {
         output.innerHTML += "Exception thrown from the forEach loop. " + error;
      }
   </script>
</body>
</html>

In the above output, users can observe that it stops printing the elements after it finds the number type element in the array.

Use the normal for-loop with the break keyword

The best solution to stop the execution of the forEach() method is to replace the forEach() loop with the normal for-loop and use the break keyword to stop its execution.

Syntax

Users can follow the syntax below to use the for-loop with the break keyword.

for ( ){
   if (condition) {
      break;
   }
}

In the above syntax, when a particular condition becomes true, we stop the execution of the for-loop using the break keyword.

Example 3

In the example below, we have defined the array of various values. We used the normal for-loop to iterate through the array, and if the array value became greater than 30, we used the break keyword to stop the execution of the for-loop.

<html>
<body>
   <h2>Using the normal for-loop with break keyword to stop the execution of for-loop. </h2>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById('output');
      let arrayElements = [10, 20, 30, 40, 50, 60, 70, 80, 90];
      output.innerHTML += "Some array elements are "
      for (let k = 0; k < arrayElements.length; k++) {
         if (arrayElements[k] > 30) {
            break;
         }
         output.innerHTML += arrayElements[k] + " , ";
      }
   </script>
</body>
</html>

method. The first approach will not break the loop but will work as a ‘continue’ statement. The second approach uses the try-catch statement to break the forEach() method. We can’t throw the error to just break the forEach() loop in real-life development. So, it is not recommended to use the first and second approaches.

In the third approach, we have replaced the forEach() method with the normal for-loop and used the break keyword. The third approach will work fine, but normal for-loop can iterate more slowly than the forEach() method through elements. So, users can also try with the array.some() and array.each() method to improve the performance.

Updated on: 12-Sep-2023

37K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements