OnlineCBT Logo OnlineCBT
JavaScript Tutorial
JAVASCRIPT · LESSON 13

Array Iteration: map, filter, reduce, forEach

By Ratan Updated: 16 Oct 2026

Transform, filter, and aggregate array data using functional iteration methods.

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive

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)); // 0

An 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

  1. Map prices to a formatted label without changing numeric source data.
  2. Filter marks below 40; expect [35].
  3. Compute an average, handling an empty array before division.
  4. Use find when you need the first matching element rather than filtering every match.

हिन्दी संकेत: पहले तय करें result नया array, एक value, या केवल side effect है; फिर method चुनें।

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
पता संपर्क करें

+91 7877547686

ई-मेल

onlinecbtportal@gmail.com

हेल्पलाइन नंबर

+91 7877547686


डाउनलोड करने के लिए क्लिक करें
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat