What are the different ways to iterate over arrays?

JavaScript

The short answer

The main methods are forEach (run code for each item), map (transform each item), filter (select items), reduce (combine into one value), for...of (loop with break support), and the classic for loop. Each has a specific use case — map for transformation, filter for selection, reduce for accumulation.

The methods

const numbers = [1, 2, 3, 4, 5];
// forEach — side effects, no return value
numbers.forEach((num) => console.log(num));
// map — transform each item, returns new array
const doubled = numbers.map((num) => num * 2); // [2, 4, 6, 8, 10]
// filter — select items that pass a test
const evens = numbers.filter((num) => num % 2 === 0); // [2, 4]
// reduce — combine all items into one value
const sum = numbers.reduce((total, num) => total + num, 0); // 15
// find — get the first item that passes a test
const firstEven = numbers.find((num) => num % 2 === 0); // 2
// some — check if at least one item passes
numbers.some((num) => num > 4); // true
// every — check if all items pass
numbers.every((num) => num > 0); // true

for...of

for (const num of numbers) {
if (num === 3) break; // can break out early
console.log(num);
}

Unlike forEach, for...of supports break and continue.

for loop

for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}

The classic for loop gives you access to the index and supports break. Use it when you need the index or need to iterate in reverse.

Which to use

  • Transform datamap
  • Filter datafilter
  • Accumulate a valuereduce
  • Side effectsforEach
  • Need to break earlyfor...of or for
  • Need the indexfor or forEach (second parameter)

Interview Tip

Show map, filter, and reduce — these are the most important. Explain when to use each one. Knowing that forEach cannot be broken out of (unlike for...of) is a good detail to mention.

Why interviewers ask this

This tests fundamental JavaScript skills. Array iteration methods are used constantly, and interviewers want to see if you pick the right method for each situation instead of using forEach for everything.