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;
}
}
}