Back to subject
JavaScript/Array Methods: map, filter, forEach, reduce

Transform, Filter, and Total a List

Practical lesson

Let's trace all three methods against the same starting array, side by side.

const nums = [1, 2, 3, 4, 5]; is the shared source. Every method below reads from this array without ever modifying it that's a deliberate, important property of all three.

nums.map(n => n * 2) runs n * 2 for every item and collects the results into a brand-new array: [2, 4, 6, 8, 10]. Notice it has the same length as the original (5 items) map always transforms, it never removes.

nums.filter(n => n % 2 === 0) checks n % 2 === 0 for every item, keeping only the ones where that's true so only 2 and 4 survive, producing [2, 4]. Unlike map, filter's result can be shorter than the original.

nums.reduce((sum, n) => sum + n, 0) starts sum at 0, then adds each number in turn: 0+1=1, 1+2=3, 3+3=6, 6+4=10, 10+5=15 the final result, 15, is the sum of the whole array, returned as a single number, not an array at all.

Three different shapes of result from the same source array a new same-length array, a new shorter array, and a single value is exactly the distinction to remember between these three methods.

Try it yourself
Code

Starter example

Code
<script>
  const nums = [1, 2, 3, 4, 5];
  const doubled = nums.map(n => n * 2);
  const evens = nums.filter(n => n % 2 === 0);
  const total = nums.reduce((sum, n) => sum + n, 0);
  document.body.innerHTML = `
    <p>Doubled: ${doubled.join(", ")}</p>
    <p>Evens: ${evens.join(", ")}</p>
    <p>Total: ${total}</p>
  `;
</script>
Live preview