3

I'm working on a homework problem using JavaScript. I have a solution that currently works, but I am sure that it is not the most efficient way to do it. I am iterating over an array to check if any element meets a certain condition. But there doesn't seem to be a way to exit the forEach() function early. In other languages, I have used break to quit a forEach loop early. Does something similar exist in JavaScript?

My code (simplified for this question):

let conditionMet = false;

numbers.forEach((number) => {
  if (number % 3 === 0) {
    conditionMet = true;
    // break; <-- does not work!
  }
});

2 Answers2

8

Rather than using Array.forEach, you can use Array.some (see docs). This function iterates over the elements of the array, checking to see if any element meets a certain condition. If an element is found that meets the condition, the function stops iteration, and returns true. If not, the function returns false. This means that you can also skip the step of initializing conditionMet to false.

Your code can therefore be simplified as:

let conditionMet = numbers.some(number => (number % 3 === 0));
Vince
  • 3,207
  • 1
  • 17
  • 28
0

You can’t break .foreach() loop unless through an exception So you can choose another tool like a simple for loop.