Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the ForEach loop allow using break and continue?

Tags:

javascript

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?

like image 659
user3450695 Avatar asked Mar 22 '14 23:03

user3450695


People also ask

Can we use break statement in forEach?

You can't break from a forEach .

How do you exit a forEach loop?

If the EXIT statement has the FOREACH statement as its innermost enclosing statement, the FOREACH keyword must immediately follow the EXIT keyword. The EXIT FOREACH statement unconditionally terminates the FOREACH statement, or else returns an error, if no FOREACH statement encloses the EXIT FOREACH statement.

How do you break a forEach loop in TypeScript?

To break a forEach() loop in TypeScript, throw and catch an error by wrapping the call to the forEach() method in a try/catch block. When the error is thrown, the forEach() method will stop iterating over the collection.

What can forEach loops be used for?

The foreach loop in C# iterates items in a collection, like an array or a list. It proves useful for traversing through each element in the collection and displaying them. The foreach loop is an easier and more readable alternative to for loop.


Video Answer


1 Answers

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.

like image 186
djechlin Avatar answered Oct 01 '22 20:10

djechlin