Array Methods (forEach, map, filter, reduce...)

The built-in tools for looping over, transforming, and summarizing arrays without writing manual loops.

What is it?

You can loop over an array with for, but most loops follow a few patterns: do something with every item, build a new array from each item, keep only some items, or combine everything into one result.

JavaScript has a built-in method for each pattern, so you don't write the loop by hand, and readers recognize the pattern from the method name.

The core ones:

  • forEach — run some code for every item (no new array)
  • map — build a new array by transforming every item
  • filter — build a new array keeping only items that pass a test
  • find — get the first item that passes a test
  • some / every — check if any / all items pass a test
  • reduce — combine every item into a single value

Explain like I'm 10

Think of an assembly line. forEach is a worker who handles every item but hands nothing back. map replaces every item with a new one. filter lets only some items through. reduce, at the end, melts everything into one final product.

Examples

forEach — run code for every item

const fruits = ["apple", "banana", "cherry"];

fruits.forEach((fruit) => {
  console.log(fruit);
});
// logs: apple, banana, cherry

forEach runs the callback once per item and returns undefined. It's for side effects (like logging), not for building a new value.

forEach — using the index and outer variables

const scores = [70, 85, 90];
let total = 0;

scores.forEach((score, index) => {
  console.log(`Test ${index + 1}: ${score}`);
  total += score;
});

console.log("Total:", total); // 245

The callback also gets the index as a second argument, and can read and update variables from the surrounding scope. forEach still returns undefined.

map — transform every item into something new

const prices = [10, 20, 30];

const withTax = prices.map((price) => price * 1.1);
console.log(withTax); // [11, 22, 33]

filter — keep only the items that pass a test

const ages = [12, 18, 25, 16, 30];

const adults = ages.filter((age) => age >= 18);
console.log(adults); // [18, 25, 30]

find, some, and every — testing items

const inventory = [
  { name: "widget", stock: 0 },
  { name: "gadget", stock: 5 },
];

const outOfStock = inventory.find((item) => item.stock === 0);
console.log(outOfStock); // { name: "widget", stock: 0 }

console.log(inventory.some((item) => item.stock === 0)); // true
console.log(inventory.every((item) => item.stock > 0));  // false

reduce — combine every item into a single value

const numbers = [1, 2, 3, 4, 5];

const total = numbers.reduce((sum, n) => sum + n, 0);
console.log(total); // 15

reduce — building an object (counting occurrences)

const words = ["apple", "banana", "apple", "cherry", "banana", "apple"];

const counts = words.reduce((tally, word) => {
  tally[word] = (tally[word] || 0) + 1;
  return tally;
}, {});

console.log(counts); // { apple: 3, banana: 2, cherry: 1 }

reduce isn't just for sums. The accumulator can be any value, including an object you build up piece by piece.

How it works

Each method takes a callback and calls it once per item, passing the item (plus its index and the whole array, if you need them).

They differ in what they do with the callback's return value: map collects it into a new array, filter uses it as a yes/no test, reduce feeds it into the next call as the accumulator, and forEach ignores it.

[1, 2, 3].map(n => n * 2)

  1 → callback(1) → 2  ┐
  2 → callback(2) → 4  ├─▶ [2, 4, 6]
  3 → callback(3) → 6  ┘

Why does it exist?

A plain for loop is flexible, but it can skip items, change things it shouldn't, or bury its purpose under bookkeeping (let i = 0, i++...). Naming the pattern (map, filter, reduce) makes the intent obvious and removes a whole class of off-by-one and indexing bugs.

When to use it

Use them when your goal matches a pattern: transform every item (map), keep some (filter), summarize into one value (reduce), or do something with each (forEach).

When not to use it

If you need to stop partway for a reason more complex than "found it," or walk two arrays in lockstep, a plain for/for...of loop can be clearer. And chaining many of these on a huge array makes several full passes; one loop that does everything in a single pass can be faster.

Common mistakes

  • Using forEach when you actually wanted map — forEach always returns undefined, so const result = arr.forEach(...) is a common bug.

  • Forgetting to provide a starting value to reduce, which can throw or misbehave on an empty array.

  • Assuming filter/map modify the original array — they always return a brand-new array, leaving the original untouched.

Practice exercises

  1. Easy:

    Use .map() to turn an array of strings into an array of their lengths.

  2. Medium:

    Use .filter() and .map() together to get the names of all users older than 18 from an array of user objects.

  3. Hard:

    Reimplement .map() yourself as a function myMap(array, callback) using a plain for loop.

Interview questions

What's the core difference between `map()` and `forEach()`?

map() collects each callback's return value into a new array. forEach() runs the callback for side effects and always returns undefined, so assigning its result is a common mistake.

What's the difference between `filter()` and `find()`?

filter() returns a new array of every element that passes (zero or many). find() returns the first match itself (not in an array), or undefined, and stops as soon as it finds one.

How do `some()` and `every()` differ, and how do they short-circuit?

some() returns true at the first element that passes; every() returns false at the first that fails. If neither stops early, some ends false and every ends true.

How does `reduce()` work?

It calls the callback once per element with an accumulator and the current element. The callback's return value becomes the next accumulator, and the final accumulator is what reduce returns.

What does `[].reduce((sum, n) => sum + n);` do, and why?

It throws TypeError: Reduce of empty array with no initial value. Without an initial value, reduce uses the first element as the accumulator and starts from the second, and an empty array has no first element.

Why does providing an initial value to `reduce()` matter even on a non-empty array?

Without one, the first element becomes the starting accumulator and the callback runs one time fewer. That silently changes the accumulator's starting type and the call count, which matters if the callback has side effects or expects a certain accumulator shape.

Which common array methods mutate the array in place, and which don't?

Mutating: push, pop, shift, unshift, splice, sort, reverse, fill, copyWithin. Non-mutating (return a new array or value): map, filter, slice, concat, reduce, find, some, every, includes.

What does this log? `const nums = [1, 2, 3, 4, 5]; console.log(nums.filter((n) => n % 2 === 0).map((n) => n * 10));`

[20, 40]. filter keeps the even numbers ([2, 4]), then map turns those into [20, 40]. Each method works on the array the previous one returned.

What does this log, and why? `console.log(["1", "2", "3"].map(parseInt));`

[1, NaN, NaN]. map passes (element, index, array), and parseInt(string, radix) treats the index as a radix. So it runs parseInt("1", 0) (radix 0 means base 10: 1), parseInt("2", 1) (radix 1 is invalid: NaN) and parseInt("3", 2) ("3" isn't a binary digit: NaN).

How would you fix the `array.map(parseInt)` bug?

Use array.map(Number) if radix doesn't matter, or array.map((str) => parseInt(str, 10)). Both stop map's index from being passed as the radix.

Why doesn't this same class of bug usually show up with `array.map(String)` or `array.map(Boolean)`?

They only use their first argument and ignore the extras map passes (index, array). parseInt is the classic trap because its second parameter changes the result.

What does this log? `const nums = [5, 1, 4, 2, 3]; nums.sort((a, b) => b - a); console.log(nums);`

[5, 4, 3, 2, 1]. A negative comparator result puts a first, positive puts b first, so b - a sorts descending. sort changes nums directly.

What is `reduceRight()`, and how does it differ from `reduce()`?

Same accumulator pattern as reduce(), but from the last element to the first. Useful when combination order matters, like right-associative operations.

What does this log? `const orders = [{ amount: 10 }, { amount: 25 }, { amount: 5 }]; const total = orders.filter((o) => o.amount > 8).map((o) => o.amount).reduce((sum, n) => sum + n, 0); console.log(total);`

35. filter keeps orders over 8 (10 and 25), map extracts their amounts, and reduce sums them: 10 + 25.

Can you `break` or `continue` out of a `forEach()` loop early?

No. forEach always runs for every element; a return in the callback only ends that one call. Use for/for...of (which supports break) to exit early.

What does this log? `[1, 2, 3].forEach((n) => { if (n === 2) return; console.log(n); });`

1 then 3. return only ends the call for n === 2, skipping its console.log; forEach continues to 3.

What does this log? `console.log([].every((x) => x > 0)); console.log([].some((x) => x > 0));`

true then false. On an empty array, every is vacuously true (no element fails), and some is false (no element passes).

Why can't `.includes()` find an object by one of its property values?

includes() uses SameValueZero equality, which for objects means same reference, not same contents. To find an object by a property, use find(), e.g. arr.find((o) => o.id === 5).

Why should `map()` always return the same number of items as the input array?

Callers rely on map transforming, not filtering. Returning undefined to "skip" items still leaves those slots (holding undefined). To drop items, use filter (possibly chained with map).

How would you implement your own version of `map()` using a plain loop, to understand what it's actually doing?

Create an empty array, loop over the input with for, call the callback with (element, index, array) each time and push its return value. That's what the built-in map does.

What's the difference between `Array.prototype.flat()` and `Array.prototype.flatMap()`?

flat(depth) flattens an existing nested array by the given depth. flatMap() maps and flattens one level in the same pass, more efficient than .map() then .flat() when the mapping produces nested arrays.

What is `Array.prototype.at()` useful for that bracket notation isn't?

arr.at(-1) reads from the end with a negative index. Brackets don't support that: arr[-1] looks up a property named "-1" and returns undefined, so you'd need arr[arr.length - 1].

Why might chaining `.filter().map()` be less efficient than a single `.reduce()` on a very large array?

Each chained method is a full pass that builds and discards an intermediate array. One reduce() (or a loop) can filter and transform in one pass. Only worth it when the array is truly large and this is a measured bottleneck.

Does `.sort()` guarantee a stable sort — that equal elements keep their relative order?

Yes. The modern ECMAScript spec requires Array.prototype.sort() to be stable: equal elements keep their original order. That matters when sorting by one key while keeping an earlier order by another.

How would you count how many times each value appears in an array using `reduce()`?

Use an object accumulator and increment a counter per value: arr.reduce((tally, v) => { tally[v] = (tally[v] || 0) + 1; return tally; }, {}).

What's a scenario where `.some()` is a better choice than `.filter().length > 0`?

When you only need to know if at least one match exists. .some() stops at the first match; .filter() scans everything and builds a full array just to check its length.