There's no built-in ability to break in forEach. To interrupt execution you would have to throw an exception of some sort. eg.
var BreakException = {};
try {
[1, 2, 3].forEach(function(el) {
console.log(el);
if (el === 2) throw BreakException;
});
} catch (e) {
if (e !== BreakException) throw e;
}
JavaScript exceptions aren't terribly pretty. A traditional for loop might be more appropriate if you really need to break inside it.
Use Array#some
Instead, use Array#some:
[1, 2, 3].some(function(el) {
console.log(el);
return el === 2;
});
This works because some returns true as soon as any of the callbacks, executed in array order, return true, short-circuiting the execution of the rest.
some, its inverse every (which will stop on a return false), and forEach are all ECMAScript Fifth Edition methods which will need to be added to the Array.prototype on browsers where they're missing.
There's no built-in ability to break in forEach. To interrupt execution you would have to throw an exception of some sort. eg.
var BreakException = {};
try {
[1, 2, 3].forEach(function(el) {
console.log(el);
if (el === 2) throw BreakException;
});
} catch (e) {
if (e !== BreakException) throw e;
}
JavaScript exceptions aren't terribly pretty. A traditional for loop might be more appropriate if you really need to break inside it.
Use Array#some
Instead, use Array#some:
[1, 2, 3].some(function(el) {
console.log(el);
return el === 2;
});
This works because some returns true as soon as any of the callbacks, executed in array order, return true, short-circuiting the execution of the rest.
some, its inverse every (which will stop on a return false), and forEach are all ECMAScript Fifth Edition methods which will need to be added to the Array.prototype on browsers where they're missing.
There is now an even better way to do this in ECMAScript2015 (aka ES6) using the new for of loop. For example, this code does not print the array elements after the number 5:
const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (const el of arr) {
console.log(el);
if (el === 5) {
break;
}
}
From the docs:
Both for...in and for...of statements iterate over something. The main difference between them is in what they iterate over. The for...in statement iterates over the enumerable properties of an object, in original insertion order. The for...of statement iterates over data that iterable object defines to be iterated over.
Need the index in the iteration? You can use Array.entries():
for (const [index, el] of arr.entries()) {
if ( index === 5 ) break;
}
How do I break out of a function while in a forEach loop?
Is there a way to exit a forEach loop early?
Videos
So I have this function that is supposed to go through a nodelist of divs being hovered and when clicked it should check if any of the squares were already checked. If they are I want to break out of the function but because i'm inside a forEach loop the return doesn't do anything. How can I check the list and break out of the function.
One scenario where I choose a for loop over the forEach() method is when I want to break out of a loop early. Imagine I had a longer list of animals and as soon as I found one that matches some criteria, I want to perform some action. If I used forEach(), it would iterate over every single animal resulting in unnecessary iterations, potentially causing performance issues depending on how long the array is. With a for loop, you have the ability to break out early and stop the loop from continuing.
https://davidtang.io/2016/07/30/javascript-for-loop-vs-array-foreach.html
You can't break from a forEach. I can think of three ways to fake it, though.
1. The Ugly Way: pass a second argument to forEach to use as context, and store a boolean in there, then use an if. This looks awful.
2. The Controversial Way: surround the whole thing in a try-catch block and throw an exception when you want to break. This looks pretty bad and may affect performance, but can be encapsulated.
3. The Fun Way: use every().
['a', 'b', 'c'].every(function(element, index) {
// Do your thing, then:
if (you_want_to_break) return false
else return true
})
You can use some() instead, if you'd rather return true to break.
Breaking out of Array#forEach is not possible. (You can inspect the source code that implements it in Firefox on the linked page, to confirm this.)
Instead you should use a normal for loop:
function recurs(comment) {
for (var i = 0; i < comment.comments.length; ++i) {
var subComment = comment.comments[i];
recurs(subComment);
if (...) {
break;
}
}
}
(or, if you want to be a little more clever about it and comment.comments[i] is always an object:)
function recurs(comment) {
for (var i = 0, subComment; subComment = comment.comments[i]; ++i) {
recurs(subComment);
if (...) {
break;
}
}
}