EasyArrays📖 Theory Question

When would you use map vs forEach vs reduce vs filter?

💡

Hint

map=transform, filter=subset, reduce=accumulate, forEach=side effects

Full Answer

  • map — transform each element, returns new array of same length
  • filter — keep matching elements, returns smaller array
  • reduce — accumulate into single value (any type)
  • forEach — side effects only, returns undefined, not chainable
const nums = [1,2,3,4,5];
nums.map(n => n * 2);                // [2,4,6,8,10]
nums.filter(n => n % 2 === 0);       // [2,4]
nums.reduce((sum, n) => sum + n, 0); // 15

// Chaining
nums.filter(n => n > 2).map(n => n ** 2); // [9,16,25]

More Arrays Questions

EasyHow do Array.find(), findIndex(), some(), and every() work?EasyHow do Array.flat() and Array.flatMap() work?EasyWhat are immutable array operations and the new ES2023 methods?

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint