Breaking out of javascript forEach
Let’s take the following example:
1 2 3 4 5 6 7 | var arr = [1,2,3,4]; arr.forEach(function(val){ if(val===2){ return false; } console.log(val); }); |
You would expect it to just print 1, instead it prints 1,3,4. You might yell WTH, but thats how the forEach method works in javascript, there is no way we can break out of this loop. The better alternative is to use the every,some method, or the plain old for loop.
1 2 3 4 5 6 7 | var arr = [1,2,3,4]; arr.every(function(val){ if(val===2){ return false; //to break out from every method, return false } console.log(val); }); |
1 2 3 4 5 6 7 | var arr = [1,2,3,4]; arr.some(function(val){ if(val===2){ return true; //to break out from some method, return true } console.log(val); }); |
This prints the desired result 1, and breaks out of the loop. Note the return values in some (return true) and every (return false) methods, if you change the return values other than the ones specified, it again leads to a different behavior.
“Don’t take your api’s for granted.”
-Rushi
-Rushi