JavaScript Array Iteration: forEach, map and filter Explained
The three workhorse array methods: forEach for side effects, map to transform every element, filter to keep the ones you want. Callback arguments, chaining, the map(parseInt) trap, mutation inside callbacks, async callbacks, thisArg, and choosing between methods and loops.
kvi5hnuCode Sprout team member6 min readOn this page
Most of what programs do with arrays falls into a few patterns: do something with each element, transform each element into something else, or select some elements. JavaScript has a method for each: forEach, map and filter. Together with reduce and the search methods (next articles), they replace most hand-written loops in modern code.

How the callback is called
All three take a callback function and call it once per element, in index order, with three arguments:
- the element,
- its index,
- the array itself.
You usually only need the first, sometimes the second; extra arguments are simply ignored by a function that doesn't declare them. None of the three methods modifies the array by itself, and all three skip holes (article 55).
forEach: do something with each element
forEach calls the function for its side effects: logging, updating the page, adding to a total, sending a request. It always returns undefined.
const cart = [
{ name: "pen", price: 2, qty: 3 },
{ name: "ink", price: 8, qty: 0 },
{ name: "pad", price: 5, qty: 2 },
];
let total = 0;
cart.forEach((item) => {
total += item.price * item.qty;
});
console.log(total);
cart.forEach((item, index) => console.log(`${index + 1}. ${item.name}`));
console.log([1, 2].forEach((x) => x * 2)); // the result is always undefined
16
1. pen
2. ink
3. pad
undefined
forEach has no way to stop early: break and continue aren't allowed in a callback, and return only ends the current call (article 43). If you need to stop, use for...of, or some/find.
map: transform every element
map builds a new array with the same length, where each element is whatever the callback returned for the corresponding input element:
const cart = [
{ name: "pen", price: 2, qty: 3 },
{ name: "ink", price: 8, qty: 0 },
{ name: "pad", price: 5, qty: 2 },
];
console.log(cart.map((item) => item.name));
console.log(cart.map((item) => item.price * item.qty));
console.log(["ana", "bo"].map((name, i) => `${i + 1}:${name.toUpperCase()}`));
[ 'pen', 'ink', 'pad' ]
[ 6, 0, 10 ]
[ '1:ANA', '2:BO' ]
Use map whenever the question is "turn this list of X into a list of Y": objects into their IDs, prices into formatted strings, rows of data into HTML elements (React's items.map(item => <li>...</li>) is exactly this).
Forgetting to return
With a block body { ... }, an arrow function needs an explicit return. Without it, map fills the result with undefined:
console.log([1, 2, 3].map((n) => { n * 2; })); // block body, no return
console.log([1, 2, 3].map((n) => n * 2)); // expression body returns
[ undefined, undefined, undefined ]
[ 2, 4, 6 ]
Returning objects
To produce new objects, return a literal wrapped in parentheses (article 52), usually with spread, so the originals stay untouched:
const items = [{ name: "pen", price: 2, qty: 3 }];
const withTotals = items.map((item) => ({ ...item, total: item.price * item.qty }));
console.log(withTotals[0], "total" in items[0]);
{ name: 'pen', price: 2, qty: 3, total: 6 } false
Changing item directly inside map (item.total = ...; return item;) mutates the original objects too, because the new array holds the same references. That defeats the purpose of map and causes subtle bugs.
The map(parseInt) trap
A famous interview question:
console.log(["1", "2", "3"].map(parseInt));
console.log(["1", "2", "3"].map(Number));
console.log(["1", "2", "3"].map((s) => parseInt(s, 10)));
[ 1, NaN, NaN ]
[ 1, 2, 3 ]
[ 1, 2, 3 ]
map passes three arguments, and parseInt accepts a second one: the radix (article 22). So the calls are parseInt("1", 0) (radix 0 means "default": 1), parseInt("2", 1) (radix 1 is invalid: NaN) and parseInt("3", 2) (3 isn't a binary digit: NaN). Passing a function directly to map is only safe when you know exactly which arguments it accepts; wrap it in an arrow function when in doubt.
filter: keep the elements you want
filter builds a new array containing only the elements for which the callback returned a truthy value (article 17). The callback is a predicate: a function that answers yes or no.
const cart = [
{ name: "pen", price: 2, qty: 3 },
{ name: "ink", price: 8, qty: 0 },
{ name: "pad", price: 5, qty: 2 },
];
console.log(cart.filter((item) => item.qty > 0).map((item) => item.name));
console.log([5, 4, 3, 2, 1].filter((_, i) => i % 2 === 0)); // by index
console.log([0, 1, "", "x", null, undefined, NaN, [], {}].filter(Boolean));
[ 'pen', 'pad' ]
[ 5, 3, 1 ]
[ 1, 'x', [], {} ]
filter(Boolean) is a popular idiom for removing falsy values, but it also removes 0 and "", which are often legitimate data. To remove only missing values, write filter((x) => x != null), which drops just null and undefined (article 23).
The result can be empty but is always a new array, and it never has holes.
Chaining
Because map and filter return arrays, you can chain them into a readable pipeline, one step per line:
const orders = [
{ id: 1, status: "paid", amount: 30 },
{ id: 2, status: "refunded", amount: 15 },
{ id: 3, status: "paid", amount: 45 },
];
const paidLabels = orders
.filter((order) => order.status === "paid")
.map((order) => `#${order.id}: $${order.amount.toFixed(2)}`);
console.log(paidLabels);
[ '#1: $30.00', '#3: $45.00' ]
Filtering before mapping does less work. Each step creates an intermediate array; for typical data sizes that's irrelevant, and for very large data, a single loop or iterator helpers (part 12) avoid the copies.
Changing the array during iteration
These methods decide the range of indexes before starting: elements added during the loop aren't visited, and removing elements shifts others past the current position:
const grow = [1, 2];
grow.forEach((x) => grow.push(x * 10)); // runs only for the original 2 elements
console.log(grow);
const shrink = [1, 2, 3, 4];
const seen = [];
shrink.forEach((x, i) => {
seen.push(x);
if (i === 0) shrink.shift(); // everything moves down one place
});
console.log(seen);
[ 1, 2, 10, 20 ]
[ 1, 3, 4 ]
Element 2 was never visited: after the shift, it moved into index 0, which had already been processed. (Unlike forEach, a for...of loop does see elements pushed during the loop; article 42.) The fix is always the same: don't modify an array while iterating over it; build a new one with filter or map.
Async callbacks don't wait
forEach ignores what its callback returns, including promises, so an async callback isn't awaited:
const done = [];
[1, 2, 3].forEach(async (n) => {
await null; // any asynchronous step
done.push(n);
});
console.log("after forEach:", done.length); // nothing has finished yet
after forEach: 0
Use for...of with await to process items one after another, or await Promise.all(items.map(async (item) => ...)) to process them concurrently (part 13).
The thisArg parameter
forEach, map, filter and most other iteration methods accept an optional second argument, which becomes this inside a regular-function callback. Arrow functions ignore it, since they use the surrounding this, so it's rarely needed today:
const settings = { factor: 3 };
console.log([1, 2].map(function (n) { return n * this.factor; }, settings));
[ 3, 6 ]
Methods or loops?
| Task | Best tool |
|---|---|
| Transform every element | map |
| Keep some elements | filter |
| Side effects for each element | forEach or for...of |
Stop early, await, break/continue | for...of |
| Need the index and the value | callback's second argument, or for (const [i, v] of arr.entries()) |
| Combine into one value | reduce (article 58) or a loop |
Methods make intent obvious at a glance (filter can only select, map can only transform) and avoid index bookkeeping. Loops are more flexible. Both are fine; many teams use methods for transformations and for...of for anything with control flow or await.
Common questions
Is map faster or slower than a for loop?
In modern engines the difference is small and rarely matters. A plain loop can win in very hot code over huge arrays, mainly because it avoids function calls and intermediate arrays. Write the clearest version first and measure before optimizing.
Should I use map just to loop?
No. If you ignore the returned array, use forEach or for...of. A map whose result is discarded misleads readers and allocates an array for nothing (ESLint's array-callback-return catches related mistakes).
Can I use these methods on strings or array-likes?
Not directly: strings have no map. Convert first with [...str] or Array.from(arrayLike), or borrow the method: the code below.
Array.prototype.map.call("abc", (c) => c.toUpperCase())
How do I map over an object?
Go through entries: the code below (article 48).
Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, f(v)]))
Summary
forEach,mapandfiltercall a callback with(element, index, array)for each element in order, skipping holes, without mutating the array themselves.forEachis for side effects, returnsundefinedand can't be stopped early.mapreturns a new array of the same length containing the callback's return values; remember thereturnin block bodies and don't mutate the elements.filterreturns a new array of the elements for which the callback returned a truthy value; beware thatfilter(Boolean)also drops0and"".["1","2","3"].map(parseInt)gives[1, NaN, NaN]because of the extra index argument.- Don't modify an array while iterating it;
forEachdoesn't await async callbacks.
Practice Questions
What does this print?
console.log([10, 20, 30].map((n, i) => n + i));
Answer
[ 10, 21, 32 ]. The second callback argument is the index.
Given this code, get the names of the adults (18 and over) in upper case.
const people = [{ name: "Ana", age: 17 }, { name: "Bo", age: 22 }, { name: "Cy", age: 30 }]
Answer
people.filter((p) => p.age >= 18).map((p) => p.name.toUpperCase())
Gives [ 'BO', 'CY' ].
What does ["10", "10", "10"].map(parseInt) return?
Answer
[ 10, NaN, 2 ]. The calls are parseInt("10", 0), parseInt("10", 1) (invalid radix) and parseInt("10", 2), which is 2 in binary.
Remove null and undefined from [0, null, 5, undefined, ""] but keep 0 and "".
Answer
[0, null, 5, undefined, ""].filter((x) => x != null)
Gives [ 0, 5, '' ]. Loose != null is true for everything except null and undefined.
Previous: JavaScript Array Elements: Indexes, length, at(), Sparse Arrays, Adding and Removing
Next: Searching JavaScript Arrays: find, findIndex, findLast, includes, indexOf, some and every

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.