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, the forEach() method is the wrong tool. Early termination may be accomplished with looping statements like forfor...of, and for...in. Array methods like every()some()find(), and findIndex() 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) as forEach callbacks.

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

Reference

Array.prototype.forEach() - JavaScript | MDN