Lesson 15 / 38

Iteration: map, filter, reduce, forEach

The functional methods that replace most loops.

forEach & map

forEach just runs code per item; map transforms every item into a new array.

const nums = [1, 2, 3];
nums.forEach(n => console.log(n * 2));

const doubled = nums.map(n => n * 2);
console.log(doubled);   // [2, 4, 6]

filter & reduce

filter keeps items that pass a test; reduce folds the whole array down to one value.

const nums = [1, 2, 3, 4, 5];
const evens = nums.filter(n => n % 2 === 0);
const total = nums.reduce((sum, n) => sum + n, 0);
console.log(evens);  // [2, 4]
console.log(total);  // 15

map vs forEach

forEach returns undefined — use it for side effects. map returns a new array — use it to transform data.

Quick check: Which method returns a new array shorter than or equal to the original?

  • map
  • filter
  • forEach
Answer

filter — `filter` only keeps items that pass the test, so the result can never be longer than the input.