Level: Intermediate | Player: 10_Arrow function
Learning Objectives
- Use
forEach,map,filter,reduce,find,some, andeveryseparately. - Know the callback parameters (element, index, array).
- Create a data pipeline using method chaining.
- Prefer a functional style that does not change the original.
- Use
reducesafely with appropriate initial values.
1. forEach and map
forEach is used for side effects (logging, DOM manipulation, etc.) and has no return value. map returns a new array.
[1, 2, 3].forEach((x) => console.log(x));
const doubled = [1, 2, 3].map((x) => x * 2); // [2,4,6]
2. filter, find, some, every
Selects elements that satisfy the conditions.
[1,2,3,4].filter((x) => x % 2 === 0); // [2,4]
[1,2,3].find((x) => x > 1); //2 (first match)
[1,2,3].some((x) => x > 2); // true
[1,2,3].every((x) => x > 0); // true
3. reduce
Collapse an array into one value. Get into the habit of specifying initial values.
const sum = [1,2,3,4].reduce((acc, x) => acc + x, 0);
const byLen = ["a","bb","ccc"].reduce((g, w) => {
(g[w.length] ??= []).push(w);
return g;
}, {});
4. Chaining
Functional pipelines are highly readable.
const users = [
{ name: "A", age: 17 },
{ name: "B", age: 22 },
{ name: "C", age: 30 },
];
const result = users
.filter((u) => u.age >= 18)
.map((u) => u.name)
.join(", ");
Core example
| file | Contents covered |
|---|---|
01_map.js |
Convert to map |
02_filter.js |
filter / find |
03_reduce.js |
Total, grouping |
04_chain.js |
filter → map → reduce chain |
⚠️ Common Mistakes
reducewas called without an initial value and a TypeError occurred with an empty array.- In
map, use only side effects and discard the return value (forEachis suitable). filterforgets to also pass truthy/falsy, not boolean.- If the chaining becomes long, worry about performance → Usually, readability comes first.
- Create
undefinedarray due to missingreturnin callback.
❓ Frequently Asked Questions (FAQ)
Q1. Performance difference with for loop? A. Most of the time, the difference is negligible. Readability comes first.
Q2. What about flat, flatMap? A. Unfold nested arrays, transform and flatten at once.
Q3. Asynchronous operation with map? A. Since the result is a Promise array, use the Promise.all(arr.map(...)) pattern.