Skip to content
Map, Filter, Reduce
step 1/7

Reading — step 1 of 7

Learn

~3 min readCollections

These three array methods replace most of the for-loops you'd otherwise write. Each takes a callback function and produces a new value — the original array is never modified. Master these and your code becomes shorter, more readable, and less buggy.

map — transform each element

js

The callback runs once per element. The return value becomes the corresponding element in the new array. Output array always has the same LENGTH as input.

With index too:

js

filter — keep elements where callback returns truthy

js

Output length is ≤ input length. The callback should return true to KEEP, false to drop.

reduce — collapse to a single value

js

The callback gets two arguments: acc (the accumulator) and n (current element). The 0 after the callback is the initial value of acc.

More examples:

js

ALWAYS pass an initial value. Without one, reduce uses the first element — fine for sums, dangerous for empty arrays (throws).

Pipelines — chain them

This is where the real power emerges:

js

Reads top-to-bottom: "start with users, KEEP active ones, EXTRACT the age, then SUM."

Other useful array methods

js

Method chains vs for-loops

Chains shine for:

  • Transformations and filters
  • Pipelines reading top-to-bottom
  • Code that fits in your head

For-loops shine for:

  • Mutating state outside the loop
  • Early-exit patterns (break)
  • Performance-critical hot loops (chains have small overhead)
  • Asynchronous iteration with await between steps

Both are tools. Don't force a chain when a for is clearer.

Common mistakes

  • Forgetting the initial value to reduce — empty arrays crash without it.
  • Using map when you don't need the result — use forEach for pure side effects.
  • Mutating inside a map callbackmap is for PURE transformations. Mutate inside forEach if you must.
  • forEach with async callbacks — doesn't await! Use for...of with await instead.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…