Kodeclik Blog


How to break out of foreach loops in Javascript

Let us write a foreach loop in Javascript to find squares of numbers from 1 to 20:
In this example, we first create an array of numbers from 1 to 20. Then, we use the forEach loop to iterate through each number and calculate its square, which is then added to the squares array. Finally, we output the array of squares using console.log. The output is:
Let us suppose we wish to update the code so that as soon as we find a square greater than 200 we exit the loop. In other words, our goal is to find the first square greater than 200.

Method 1: Use the “every” loop and return false

Here is a code to break out of the loop. The first thing to note is that instead of the foreach, we use the “every” construct. Secondly, note that as soon as we return “false” we break out of the loop.
The code is similar to the previous code except for the replacement of “foreach” with “every”. Further, inside the loop, we compute the square and then check if the square is more than 200. If it is more than 200 we return false (which exits the loop). Otherwise we return true (which continues the loop). The output is:
Thus we see that the loop exited as soon as we found a number greater than 200.

Method 2: Use the “forEach” loop and throw an 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. In this approach, we can keep the forEach() method (i.e., not necessary to convert it to every()).
Here is the updated code for this situation:
In this example, we use a try...catch block to catch the error thrown when a square greater than 200 is found. This will effectively exit the loop. The squares of the numbers up to the point where the square is greater than 200 will be stored in the squares array and then outputted.
Note that in this approach, the square 225 is not found because the exception is thrown by then. (If you wish 225 to be included you should add a squares.push statement before the exception is thrown). The output is thus:
Thus there are two approaches to break out of foreach loops. The first approach is to convert them to “every” loops and return false. The second is to retain the foreach loops and throw an exception.
If you liked this blogpost, learn how to exit a function in Javascript!
Want to learn Javascript with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.
  • ABOUT

Copyright @ Kodeclik 2024. All rights reserved.