What are the different ways to iterate over arrays?
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
1const numbers = [1, 2, 3, 4, 5];23// forEach — side effects, no return value4numbers.forEach((num) => console.log(num));56// map — transform each item, returns new array7const doubled = numbers.map((num) => num * 2); // [2, 4, 6, 8, 10]89// filter — select items that pass a test10const evens = numbers.filter((num) => num % 2 === 0); // [2, 4]1112// reduce — combine all items into one value13const sum = numbers.reduce((total, num) => total + num, 0); // 151415// find — get the first item that passes a test16const firstEven = numbers.find((num) => num % 2 === 0); // 21718// some — check if at least one item passes19numbers.some((num) => num > 4); // true2021// every — check if all items pass22numbers.every((num) => num > 0); // true
for...of
1for (const num of numbers) {2 if (num === 3) break; // can break out early3 console.log(num);4}
Unlike forEach, for...of supports break and continue.
for loop
1for (let i = 0; i < numbers.length; i++) {2 console.log(numbers[i]);3}
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 data →
map - Filter data →
filter - Accumulate a value →
reduce - Side effects →
forEach - Need to break early →
for...oforfor - Need the index →
fororforEach(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.