Hiprup

What is the difference between map and forEach?

Both loop an array and run a function per item, but differ in their return value.

  • map — returns a new array of transformed values; chainable.

  • forEach — returns undefined; only for side effects.

Use map when you want a new array; forEach when you just need to do something per item.

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

// map — returns new array
const doubled = nums.map(n => n * 2); // [2, 4, 6, 8, 10]

// forEach — returns undefined
const result = nums.forEach(n => console.log(n)); // undefined!

// map is chainable
const processed = nums
  .filter(n => n > 2)
  .map(n => n * 10)
  .sort((a, b) => b - a); // [50, 40, 30]

// forEach for side effects only
nums.forEach(n => document.createElement('p').textContent = n);

map returns [2,4,6,8,10]. forEach returns undefined. map is chainable (filter+map+sort). forEach is for side effects only. Using map and ignoring the result wastes memory (creates unused array).

map = transform + return. forEach = iterate + no return. Do not use map for side effects (wasteful). forEach cannot break — use for...of if you need early exit.

What is the difference between map and forEach? | Hiprup