Home > Web Front-end > JS Tutorial > body text

How to stop forEach() method in JavaScript?

WBOY
Release: 2023-08-23 19:53:02
forward
977 people have browsed it

How to stop forEach() method in JavaScript?

In JavaScript, programmers can use the forEach() method to iterate over an array of elements. We can call the callback function, passing it as an argument to the forEach() method for each array element.

Sometimes, we may need to stop the forEach() loop after executing the callback function. We can use the 'break' keyword in a normal loop to stop it as shown below.

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

But we cannot use the 'break' keyword in the forEach() method.

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

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

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

Use return keyword

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

grammar

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

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

In the above syntax, if the condition becomes true, the code of the element's callback function will not be executed.

The Chinese translation of

Example 1

is:

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>
Copy after login

The "return" keyword will not interrupt the forEach() method, but it will function as a continuation keyword if the condition is true.

Stop the forEach() loop by throwing an exception

Another way to stop the execution of the forEach() loop is to use a try-catch statement. When we want to stop the execution of the forEach() method, we can throw an error. Additionally, we can catch errors in a ‘catch’ block. We can execute any code we need to execute after the forEach() method in the ‘finally’ block.

grammar

Users can use the try-catch statement according to the following syntax to stop the forEach() method.

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

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

The Chinese translation of

Example 2

is:

Example 2

In the following example, we use the forEach() method with a try-catch statement. In the callback function of the forEach() method, we check the element type and if we find any element of type "number", we throw an error.

So, it will stop executing 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>
Copy after login

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

Use ordinary for loop and break keyword

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

grammar

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

for ( ){
   if (condition) {
      break;
   }
}
Copy after login

In the above syntax, we use the break keyword to stop the execution of the for loop when a specific condition becomes true.

The Chinese translation of

Example 3

is:

Example 3

In the example below, we define an array containing various values. We use a normal for loop to traverse the array, and if the value of the array is greater than 30, we use 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>
Copy after login

method. The first method does not break the loop, but acts as a "continue" statement. The second method uses a try-catch statement to interrupt the forEach() method. In actual development, we cannot throw errors to interrupt the forEach() loop. Therefore, the first and second methods are not recommended.

In the third method, we replace the forEach() method with an ordinary for loop and use the break keyword. The third method will work fine, but a normal for loop may be slower than the forEach() method when iterating through the elements. Therefore, users can also try array.some() and array.each() methods to improve performance.

The above is the detailed content of How to stop forEach() method in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!