Quiz

What are the different methods for iterating over an array?

Topics
JavaScript

TL;DR

Choose an iteration construct by the result and control flow you need: map() transforms into a new array, filter() selects, reduce() combines, some() / every() answer conditions, and find() locates one item. Use for...of or an indexed for loop when you need break, continue, sequential await, or precise index control. Use forEach() for synchronous side effects only; it ignores returned Promises and cannot be stopped early.


Different methods for iterating over an array

For loop

The for loop is one of the most basic and versatile ways to iterate over an array. It allows you to control the iteration process completely.

const array = [1, 2, 3, 4, 5];
for (let i = 0; i < array.length; i++) {
console.log(array[i]);
}

For...of loop

The for...of loop is a more modern and readable way to iterate over arrays and other iterable objects.

const array = [1, 2, 3, 4, 5];
for (const element of array) {
console.log(element);
}

forEach method

The forEach method executes a provided function once for each array element.

const array = [1, 2, 3, 4, 5];
array.forEach((element) => {
console.log(element);
});

Avoid this asynchronous trap:

// Does not wait for the async callbacks.
await files.forEach(async (file) => saveFile(file));
// Sequential, useful when order or rate limiting matters.
for (const file of files) {
await saveFile(file);
}
// Concurrent, useful when operations are independent and concurrency is safe.
await Promise.all(files.map((file) => saveFile(file)));

For a large collection, unbounded Promise.all() can overload a service or exhaust resources; use a concurrency limit when necessary.

Map method

The map method creates a new array populated with the results of calling a provided function on every element in the calling array.

const array = [1, 2, 3, 4, 5];
const newArray = array.map((element) => element * 2);
console.log(newArray); // [2, 4, 6, 8, 10]

Filter method

The filter method creates a new array with all elements that pass the test implemented by the provided function.

const array = [1, 2, 3, 4, 5];
const filteredArray = array.filter((element) => element > 2);
console.log(filteredArray); // [3, 4, 5]

Reduce method

The reduce method executes a reducer function on each element of the array, resulting in a single output value.

const array = [1, 2, 3, 4, 5];
const sum = array.reduce(
(accumulator, currentValue) => accumulator + currentValue,
0,
);
console.log(sum); // 15

Further reading

Exercises

Check your understanding
Beta
Check your understanding Exercise
Check your understanding Exercise

Which iteration-method choices match the stated goal? Select all that apply.