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!
}
});
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With