TExcelTAD
Home › JavaScript › JS Array Iteration

JavaScript Array Iteration

Array iteration methods run a function on every element. Instead of writing a loop with an index, you describe what should happen to each element: transform it (map), keep it or not (filter), combine everything into one result (reduce), or just do something with it (forEach). These methods are the backbone of modern JavaScript data handling.

forEach — do something with each element

js · try it yourself
const fruits = ["kiwi", "mango", "plum"];
fruits.forEach((fruit, index) => {
  console.log(`${index}: ${fruit}`);
});
0: kiwi
1: mango
2: plum

The callback receives (element, index, array); use as many parameters as you need. forEach returns undefined and can't be stopped early — use a for…of loop with break if you need that.

map — transform each element

map builds a new array of the same length, where each element is whatever the callback returns:

js · try it yourself
const prices = [10, 25, 4];
const withTax = prices.map((p) => p * 1.2);
const labels = prices.map((p, i) => `#${i + 1}: ${p.toFixed(2)} €`);
console.log(withTax);
console.log(labels);
console.log(prices);   // unchanged
[ 12, 30, 4.8 ]
[ '#1: 10.00 €', '#2: 25.00 €', '#3: 4.00 €' ]
[ 10, 25, 4 ]

filter — keep some elements

filter returns a new array containing only the elements for which the callback returns a truthy value:

js · try it yourself
const temps = [18, 25, 31, 12, 28];
const hotDays = temps.filter((t) => t >= 25);
console.log(hotDays);
console.log(["a", "", "b", null, "c"].filter(Boolean));   // drop falsy values
[ 25, 31, 28 ]
[ 'a', 'b', 'c' ]

reduce — combine into one value

reduce(callback, initialValue) walks through the array carrying an accumulator. The callback receives (accumulator, element) and returns the new accumulator. The final accumulator is the result:

js · try it yourself
const cart = [
  { item: "Book", price: 12, qty: 2 },
  { item: "Pen", price: 1.5, qty: 4 },
  { item: "Bag", price: 30, qty: 1 },
];

const total = cart.reduce((sum, line) => sum + line.price * line.qty, 0);
console.log("Total:", total);

const words = ["apple", "avocado", "banana", "blueberry", "cherry"];
const byLetter = words.reduce((groups, w) => {
  const key = w[0];
  (groups[key] ??= []).push(w);
  return groups;
}, {});
console.log(byLetter);
Total: 60
{
  a: [ 'apple', 'avocado' ],
  b: [ 'banana', 'blueberry' ],
  c: [ 'cherry' ]
}

Tip: Always pass an initial value to reduce. Without one, the first element becomes the starting accumulator, and an empty array throws a TypeError.

For grouping specifically, newer engines also offer Object.groupBy(array, fn).

Chaining

Because map and filter return arrays, you can chain them into a readable pipeline:

js · try it yourself
const orders = [
  { id: 1, status: "paid", amount: 40 },
  { id: 2, status: "open", amount: 15 },
  { id: 3, status: "paid", amount: 22.5 },
  { id: 4, status: "refunded", amount: 9 },
];

const paidIds = orders.filter((o) => o.status === "paid").map((o) => o.id);
const revenue = orders
  .filter((o) => o.status === "paid")
  .reduce((sum, o) => sum + o.amount, 0);

console.log(paidIds, revenue);
[ 1, 3 ] 62.5

Iteration method summary

Method Returns Use it to…
forEach(fn) undefined perform side effects (logging, DOM updates)
map(fn) new array, same length transform every element
filter(fn) new array, same or shorter keep matching elements
reduce(fn, init) any single value sum, count, group, build objects
reduceRight(fn, init) any single value like reduce, from the end
some(fn) / every(fn) boolean test elements
find(fn) / findIndex(fn) element / index locate one element
flatMap(fn) new flattened array map then flatten one level
entries() / keys() / values() iterator loop with for…of

Test yourself

What does [1, 2, 3].map(n => n * n) return?

  1. 14
  2. [1, 4, 9]
  3. [2, 4, 6]
  4. undefined

What does [1, 2, 3, 4].reduce((a, n) => a + n, 10) return?

  1. 10
  2. 20
  3. 24
  4. [11, 12, 13, 14]

What does forEach return?

  1. A new array
  2. The original array
  3. undefined
  4. The number of elements