I am trying to break out of an inner foreach loop using JavaScript/jQuery.
result.history.forEach(function(item) {
loop2:
item.forEach(function(innerItem) {
console.log(innerItem);
break loop2;
});
});
This is resulting in the error 'Unidentified label loop2'
. it appears to be right before the loop which was what other questions were saying was the issue.
What am I doing wrong and how do I fix it?
Edit: Correct, the foreach loop cant break in this way but a regular for loop can. This is working:
result.history.forEach(function(item) {
loop2:
for (var i = 0; i < item.length; i++) {
var innerItem = item[i];
console.log(innerItem);
break loop2;
}
});
Iirc a break; statement will only break the closest loop, so issuing a break; in the inner loop should continue with the next item on the outer loop. The OP wants to skip the remaining code on the outer loop and continue its execution at the top of the outer loop.
To break out of a for loop, you can use the endloop, continue, resume, or return statement. endfor; If condition is true, statementlist2 is not executed in that pass through the loop, and the entire loop is closed.
Using break in a nested loop In a nested loop, a break statement only stops the loop it is placed in. Therefore, if a break is placed in the inner loop, the outer loop still continues. However, if the break is placed in the outer loop, all of the looping stops.
'return' doesn't stop looping The reason is that we are passing a callback function in our forEach function, which behaves just like a normal function and is applied to each element no matter if we return from one i.e. when element is 2 in our case.
If you need to be able to break an iteration, use .every()
instead of .forEach()
:
someArray.every(function(element) {
if (timeToStop(element)) // or whatever
return false;
// do stuff
// ...
return true; // keep iterating
});
You could flip the true
/false
logic and use .some()
instead; same basic idea.
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