Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Continue" in Lodash forEach

I was looking over the differences between the Underscore and Lodash libraries and I came upon one issue regarding _.each / _.forEach.

In Underscore, the _.each function cannot break out of the looping. When using return false, it only worked as a "continue" statement. (which was the intended functionality in my case) = It forces the next iteration of the loop to take place, skipping any code in between.

In Lodash, on the other hand, returning false tells _.forEach() that this iteration will be the last. Is there a way to make the "continue" behavior also functional in Lodash?

Thanks.

like image 733
IceWhisper Avatar asked Apr 06 '17 08:04

IceWhisper


People also ask

Can I use continue in forEach?

To continue in a JavaScript forEach loop you can't use the continue statement because you will get an error. Instead you will need to use the return statement in place of the continue statement because it will act in the same way when using a forEach because you pass in a callback into the forEach statement.

How do you break a forEach loop in Lodash?

Javascript. Conclusion: Hence to break Lodash forEach loop we have to return false from the callback function.

How do you wait for forEach to complete in JavaScript?

To wait for . forEach() to complete with JavaScript, we should replace forEach with a for-of loop. const myAsyncLoopFunction = async (array) => { const allAsyncResults = []; for (const item of array) { const asyncResult = await asyncFunction(item); allAsyncResults. push(asyncResult); } return allAsyncResults; };


1 Answers

In Lodash, on the other hand, returning false tells _.forEach() that this iteration will be the last. Is there a way to make the "continue" behavior also functional in Lodash?

You could return true, or just a single return (which returns undefined), this value is different from needed false for "exit iteration early by explicitly returning false."

_.forEach([1, 2, 3, 4, 5], function (a) {      if (a < 3) return;       // continue      console.log(a);      if (a > 3) return false; // break      // return undefined;     // continue, undefined is the standard value of ending a function  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
like image 86
Nina Scholz Avatar answered Sep 20 '22 18:09

Nina Scholz