Kodeclik Logo

Our Programs

Courses

Gifting

Learn More

Schedule

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:

// Array to hold the numbers
let numbers = []; 

// Array to hold the squares
let squares = []; 

// Populate the numbers array with integers from 1 to 20
for (let i = 1; i <= 20; i++) {
  numbers.push(i);
}

// Use the forEach loop to calculate the squares
numbers.forEach(number => {
// Calculate the square and push it to the squares array
  squares.push(number * number); 
});

// Output the array of squares
console.log(squares);

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:

[1, 4, 9, 16, 25, 36, 49, 64, 
81, 100, 121, 144, 169, 196, 
225, 256, 289, 324, 361, 400]

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.

How to break out of a foreach loop in Javascript

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.

// Array to hold the numbers
let numbers = []; 

// Array to hold the squares
let squares = []; 

// Populate the numbers array with integers from 1 to 20
for (let i = 1; i <= 20; i++) {
  numbers.push(i);
}

// Use the forEach loop to calculate the squares
numbers.every(number => {
  let sq = number * number;
  squares.push(sq);
  if (sq > 200) {
    return false;
  }
  return true;
});

// Output the array of squares
console.log(squares);

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:

[1, 4, 9, 16, 25, 36, 49, 64, 
81, 100, 121, 144, 169, 196, 225]

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:

// Array to hold the numbers
let numbers = []; 

// Array to hold the squares
let squares = []; 

// Populate the numbers array with integers from 1 to 20
for (let i = 1; i <= 20; i++) {
  numbers.push(i);
}

try {
  numbers.forEach(number => {
    let square = number * number;
    if (square > 200) {
      throw new Error('Square is greater than 200'); 
      // Exit the loop
    }
    squares.push(square);
  });
} catch (e) {
  // Do nothing, the loop will exit when a square > 200 is found
}

console.log(squares);

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:

[1, 4, 9, 16, 25, 36, 49, 64, 
81, 100, 121, 144, 169, 196]

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.

Kodeclik sidebar newsletter

Join our mailing list

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

About

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

Copyright @ Kodeclik 2024. All rights reserved.