Skip to content

forEach()

forEach() executes a function for each element in the array. It’s used for side effects (logging, updating external state) rather than creating new values.

array.forEach((element, index, array) => {
// side effect
});
const fruits = ['apple', 'banana', 'orange'];
fruits.forEach((fruit, index) => {
console.log(`${index}: ${fruit}`);
});
// 0: apple
// 1: banana
// 2: orange
// Use forEach for side effects
fruits.forEach(fruit => console.log(fruit));
// Use map for transformation
const lengths = fruits.map(fruit => fruit.length);
  • Iterates over each element
  • Returns undefined — cannot chain
  • Cannot break or continue (use for…of instead)
  • Use for side effects, not transformations