Javascript forEach
Caveats
-
There is no way to stop or break a
forEach()loop other than by throwing an exception. If you need such behavior, theforEach()method is the wrong tool. Early termination may be accomplished with looping statements likefor,for...of, andfor...in. Array methods likeevery(),some(),find(), andfindIndex()also stops iteration immediately when further iteration is not necessary. -
forEach()expects a synchronous function — it does not wait for promises. Make sure you are aware of the implications while using promises (or async functions) asforEachcallbacks.
const ratings = [5, 4, 5];
let sum = 0;
const sumFunction = async (a, b) => a + b;
ratings.forEach(async (rating) => {
sum = await sumFunction(sum, rating);
});
console.log(sum);
// Naively expected output: 14
// Actual output: 0