Differences between JavaScript map, filter, reduce, and for...of

  • map: creates a new array by transforming each element.
  • filter: creates a new array with only elements that pass a condition.
  • reduce: reduces all elements into a single value.
  • for...of: a simple loop to go through each element without creating a new array.
const nums = [1, 2, 3, 4, 5];

// map → multiply by 2
const doubled = nums.map(n => n * 2);
// [2, 4, 6, 8, 10]

// filter → keep evens
const evens = nums.filter(n => n % 2 === 0);
// [2, 4]

// reduce → sum
const sum = nums.reduce((acc, n) => acc + n, 0);
// 15

// for...of → plain iteration
for (const n of nums) {
  console.log(n); // 1, 2, 3, 4, 5
}
MethodReturn ValuePerformanceBest Use CaseCreates New Array?
mapArray (same length)MediumTransform all elements✅ Yes
filterArray (≤ length)MediumSelect elements matching a condition✅ Yes
reduceSingle valueMedium-SlowerAggregate/combine into one result❌ No
for...ofNone (just loop)FastestPlain iteration, side-effects, max performance❌ No