1

How to break _.each() loop? Tried with _.every(), it is looping through the data only once.

Sample code:

    _.each([1,2,3,4,5],function(num){ 
       if(num < 3)
          console.log(num)
       else{
          console.log(num);
          return false;
       }
   });

Output: 1 2 3 4 5

    _.every([1,2,3,4,5],function(num){ 
       if(num < 3)
          console.log(num)
       else{
          console.log(num);
          return false;
       }
   });

Output: 1 false

smita chougale
  • 235
  • 5
  • 19

1 Answers1

2

You cannot escape from the functional forEach loop.

Consider using a regular for loop instead.

const arr = [1,2,3,4,5];

for (let i = 0; i < arr.length; ++i) {
    const num = arr[i];
    if(num < 3) {
       console.log(num)
    } else {
       console.log('break out');
       break;
    }
}
Naftali
  • 144,921
  • 39
  • 244
  • 303
  • 1
    In fact you can.. `var break = false; _.each([...],(num)=>{ if(break) return [...] break = true; });` – Bellian Jul 25 '17 at 15:24
  • @Bellian it will still be in the loop though an then have an extra if check for break..... – Naftali Jul 25 '17 at 15:24
  • Indeed i cant advise to do so but it is possible. Just for completion (didn't downvote btw..) – Bellian Jul 25 '17 at 15:26
  • 1
    But again, that is not a loop break. Still looping ;-) – Naftali Jul 25 '17 at 15:27
  • True. But does not perform :/ – Bellian Jul 25 '17 at 15:29
  • @Bellian If you want the ugly "solution" for breaking from a `each` callback "loop", use exceptions. See [this question](https://stackoverflow.com/q/2641347/1048572) for details. But really, one should just not use `forEach` in that case. – Bergi Jul 25 '17 at 15:48