I have something like this:
function myRatherLongFunction(){
... some computation ...
var items = ... some array ...
if (some condition) return something
... more computations ...
if (some condition) return something
... more computations ...
for (var i=0; i<items.length; i++){
var item = items[i];
var blah1 = ...something...
var blah2 = ...something...
var blah3 = ...something...
if (loremIpsum(i,item,blah1,blah2,blah3)) {
return someFunction(i,item,blah1,blah2,blah3);
}
}
... even more computations ...
}
Though I think (or feel) that .forEach
is somewhat 'overhyped', I do like to use it, since it often saves typing, among other things. So, in above situation, how would I do that (talking about the for
loop) with .forEach
?
You see, if the items
array has, say, 10 million entries, and I find something right at the beginning, I sure do not want to continue running a pointless search and make my code slow.
I know about Array.find
and Array.findIndex
, but they just return item
or i
, respectively.
I know I could throw an error (with message "item found") inside the .forEach
callback function when the item is found, and then catch an error (with that same message) just outside the .forEach
, but that all would be more typing than the straight for loop, so I do not want to do it that way. Any way this can be done with less typing (than straight for
loop), not more?
Using .find
or .findIndex
, storing blah1
etc somehow, and retrieving the stored values after .find
returns (so someFunction
can be called thereafter) can certainly be made to work, but I doubt very much that that would be less typing compared to just keeping good old retro style.
UPDATE
Please consider Bergi's comment to be the accepted answer.