Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using break and continue in each() and forEach()

Tags:

javascript

I am not sure I understand the value of the functional style looping/mapping if we can't use the break and continue keywords.

I can do this:

collections.users.models.forEach(function(item, index) {
    //can't use break or continue...?
});

or I can do this:

for (var i = 0; i < collections.users.models.length; i++) {
     if (user.username === collections.users.models[i].username) {
         app.currentUser = collections.users.models[i];
         break;
     }
}

what's the advantage of the functional call if I can't use the break or continue keywords?

like image 652
Alexander Mills Avatar asked Dec 19 '22 02:12

Alexander Mills


2 Answers

.each() or .forEach() are less flexible than a plain for loop. They just are.

As you have discovered, they offer you less control over the looping. They are a convenience ONLY when you want to iterate the entire set or when it really helps you to automatically have a new function context for your loop iteration code (sometimes useful in async operations) or when you enjoy the more declarative coding in that using the method expresses your coding intent a little more clearly and succinctly than the for loop. .forEach() will also automatically skip sparse elements of an array.

Other than those features, they are just a reduction in typing that sacrifices some looping control. Use them when you like one of the advantages and don't use it when you need more looping control.


FYI, for Javascript arrays, .some() and .every() attempt to get you back some looping control, though they are still not as flexible as a for loop.

If you use .some(), you can return true; to be the equivalent of break; (since that will stop the looping) and you can just return; to be the equivalent of continue; (since that will return from the callback and advance to the next iteration).

like image 141
jfriend00 Avatar answered Dec 24 '22 01:12

jfriend00


To be honest, there is not much of an "advantage" so much as a convenience. You can call return to force yourself out of a single iteration of a forEach loop, but this is not the same as the native for because you are still invoking a function. The convenience comes in the form of not having to define the parameterization of your loop (ie. start point, end point, step size) as well as providing the value of the index and item in the items iterated over.

It is worth mentioning that this convenience comes at the cost of for loop control (ie. start point, end point, step size), backwards iteration, the ability to break the entire loop, a small performance impedance, and yes, even cross browser compliance.

like image 23
BTC Avatar answered Dec 24 '22 03:12

BTC