What are the different ways to iterate over arrays?
JavaScriptThe 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 valuenumbers.forEach((num) => console.log(num));// map — transform each item, returns new arrayconst doubled = numbers.map((num) => num * 2); // [2, 4, 6, 8, 10]// filter — select items that pass a testconst evens = numbers.filter((num) => num % 2 === 0); // [2, 4]// reduce — combine all items into one valueconst sum = numbers.reduce((total, num) => total + num, 0); // 15// find — get the first item that passes a testconst firstEven = numbers.find((num) => num % 2 === 0); // 2// some — check if at least one item passesnumbers.some((num) => num > 4); // true// every — check if all items passnumbers.every((num) => num > 0); // truefor...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 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.