Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
43
rated 0 times [  45] [ 2]  / answers: 1 / hits: 20454  / 10 Years ago, sat, march 22, 2014, 12:00:00

Does the ForEach loop allow us to use break and continue?



I've tried using both but I received an error:



Illegal break/continue statement


If it does allow, how do I use them?


More From » javascript

 Answers
30

No, it doesn't, because you pass a callback as a return, which is executed as an ordinary function.



Let me be clear:



var arr = [1,2,3];
arr.forEach(function(i) {
console.log(i);
});

// is like

var cb = function(i) {
console.log(i);
// would break here do anything?
// would continue here do anything?
// of course not.
}

for(var j = 0; j < arr.length; j++) {
cb(arr[j]);
}


All forEach does is call a real, actual function you give to it repeatedly, ignore how it exits, then calls it again on the next element.



In that callback function if you return it will incidentally work like continue in the case of forEach. Because the rest of the function won't execute that time, and it will be called again. There is no analogue of break.



Ruby supports this flexibility, using blocks/procs instead of methods/lambdas.



Per Mozilla's documentation:




Note : There is no way to stop or break a forEach loop. The solution is to use Array.every or Array.some. See example below.




every and some are exactly like forEach, except they pay attention to the return value of the callback. every will break on a falsey value and some will break on a truthy value, since they shortcircuit. They are exactly analogous to && and ||. && tests whether every expression is truthy, || tests for whether some is, which should help you remember how short-circuiting works with every and some. When in doubt, try it.


[#71839] Friday, March 21, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
darennevina

Total Points: 422
Total Questions: 128
Total Answers: 105

Location: Comoros
Member since Tue, Mar 14, 2023
1 Year ago
;