Choose an array operation by its result
map transforms elements into a new array. filter selects elements into a new array. reduce combines elements into one accumulated result. forEach performs an action for each visited element and returns undefined. These tools are not interchangeable.
const marks = [35, 40, 82];
const labels = marks.map(mark => mark + '%');
const passed = marks.filter(mark => mark >= 40);
const total = marks.reduce((sum, mark) => sum + mark, 0);
console.log(labels); // ['35%', '40%', '82%']
console.log(passed); // [40, 82]
console.log(total); // 157
marks.forEach(mark => console.log(mark));Return from the callback
A map callback with a block body must return its value. Without return, it creates undefined entries. A filter callback should return a condition. Returning from a forEach callback does not break the whole traversal or return a value from the surrounding function.
Empty arrays and reduce
console.log([].reduce((sum, value) => sum + value, 0)); // 0An explicit initial accumulator defines the empty case. reduce without an initial value throws for an empty array. Use an initial object or array when the intended accumulator is a collection, and avoid accidental mutation of unrelated state.
Transformation is shallow
A new array from filter still contains references to the selected original objects. map can create new objects explicitly, such as students.map(student => ({ ...student, reviewed: true })). Nested properties remain shared unless you deliberately copy them too.
Async caveat
forEach does not await promises returned by an async callback. For sequential asynchronous work, use an appropriate for...of loop with await. For independent parallel work, map to promises and await Promise.all, considering error and load limits.
Practice
- Map prices to a formatted label without changing numeric source data.
- Filter marks below 40; expect [35].
- Compute an average, handling an empty array before division.
- Use find when you need the first matching element rather than filtering every match.
हिन्दी संकेत: पहले तय करें result नया array, एक value, या केवल side effect है; फिर method चुनें।