What are the different methods for iterating over an array?
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.
For...of loop
The for...of
loop is a more modern and readable way to iterate over arrays and other iterable objects.
forEach method
The forEach
method executes a provided function once for each array 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.
Filter method
The filter
method creates a new array with all elements that pass the test implemented by the provided function.
Reduce method
The reduce
method executes a reducer function on each element of the array, resulting in a single output value.