Hiprup

What is the difference between map() and forEach()?

Both loop over an array and run a function on each item, but differ in what they return.

  • map — returns a new array of transformed values. Use it when you want a result.

  • forEach — returns undefined; it's only for side effects like logging or updating something.

  • Chaining — map can be chained (e.g. with filter); forEach cannot.

Rule of thumb: use map to build a new array, forEach to just do something per item.

const numbers = [1, 2, 3, 4, 5];

// map - returns new array
const doubled = numbers.map(n => n * 2); // [2, 4, 6, 8, 10]
console.log(numbers); // [1, 2, 3, 4, 5] — unchanged

// forEach - returns undefined
const result = numbers.forEach(n => console.log(n)); // logs 1,2,3,4,5
console.log(result); // undefined

// Chaining (only map)
const processed = numbers
  .filter(n => n > 2)
  .map(n => n * 10); // [30, 40, 50]

// forEach for side effects
numbers.forEach(n => {
  document.getElementById(`item-${n}`).textContent = n;
});

map creates [2,4,6,8,10] — original unchanged. forEach logs each number but returns undefined. map is chainable (filter+map). forEach is for side effects (DOM updates). Using map and ignoring the result is wasteful — use forEach.

map = transform + return new array, forEach = side effects + return undefined. The chainability of map is the key practical difference.

Do not use map if you ignore the return value — use forEach.

What is the difference between map() and forEach()? | Hiprup