Quiz

What are the different methods for iterating over an array?

Topics
JavaScript
Edit on GitHub

TL;DR

There are several methods to iterate over an array in JavaScript. The most common ones include for loops, forEach, map, filter, reduce, and for...of. Each method has its own use case. For example, for loops are versatile and can be used for any kind of iteration, while forEach is specifically for executing a function on each array element. map is used for transforming arrays, filter for filtering elements, reduce for accumulating values, and for...of for iterating over iterable objects.


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);
});

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

Edit on GitHub