2

I was just using forEach method in JavaScript to sum up all the elements in an array. Suddenly felt the need to break out of the loop on certain conditions, for example putting a limit on the sum to be calculated. I have come up with the following solution. Point me if I am wrong.

small edit to this

function foreach(a) {
 var sum = 0;
 var breakException = {error:"stop it"};
 try {
    a.forEach(function (v) {
        sum += v;
        console.log(sum);
        if(sum>5) throw breakException.error;
    });
    return sum;
}
catch(e) {
    if(e!=breakException){
        throw e;
    }
}
}
optimus
  • 834
  • 1
  • 10
  • 22

3 Answers3

8

forEach is not supposed to break. If you 'd like to break a forEach-like loop, try every or some, which let you break out of the loop.

A possible way to re-write your code could be

var sum = 0;

yourArray.some(function (item) {
    if (sum > 5) {
        return true;
    }
    sum += item;
});
Paris
  • 6,323
  • 7
  • 31
  • 49
  • @AmitJoki well you can use `.some()` as if it were a `.forEach()` except you have to keep returning `false` for it to continue. As soon as the callback returns `true`, the iterations stops. The return value can be ignored. (I guess if you don't `explicitly` return `false` and just let the return value be `undefined`, that works too.) – Pointy Mar 28 '15 at 17:01
  • @Pointy got it. That's why I removed my first comment. – Amit Joki Mar 28 '15 at 17:02
  • i know there are alternatives...... but if we are fetching large number of records in an array and suppose there is a forEach loop, then what will be the new way to break it at some point – optimus Mar 28 '15 at 17:09
  • @optimus, you seem to be missing the point. If you want to break out of a loop you would _need_ to use one the alternative given in the answers here. – Andy Mar 28 '15 at 17:20
3

You can't break out of a forEach. Just use a normal loop

for(var i = 0; i < a; i++){
   sum += a[i];
   if(sum > 5) break;
}
Amit Joki
  • 58,320
  • 7
  • 77
  • 95
1

Your current code seems a little silly.

Your try/catch block is useless, as you don't ever throw an error for the catch block to catch, then re-throw (?) and you don't need to alert("break"); to stop a script.

You can't break out of a forEach loop anyway, I think you'd just want to use a normal for loop:

function sum(list){
  var sum = 0;
  for (var i = 0, len = list.length; i < len; i++){
    sum += list[i];
    if (sum > 5){
      break;
    }
  }
  return sum;
}
theonlygusti
  • 11,032
  • 11
  • 64
  • 119