Reading — step 1 of 7
Learn
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
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:
filter — keep elements where callback returns truthy
Output length is ≤ input length. The callback should return true to KEEP, false to drop.
reduce — collapse to a single value
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:
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:
Reads top-to-bottom: "start with users, KEEP active ones, EXTRACT the age, then SUM."
Other useful array methods
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
awaitbetween 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
mapwhen you don't need the result — useforEachfor pure side effects. - Mutating inside a
mapcallback —mapis for PURE transformations. Mutate insideforEachif you must. forEachwithasynccallbacks — doesn't await! Usefor...ofwithawaitinstead.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…