JavaScript forEach()

The forEach() method calls a function and iterates over the elements of an array. The forEach() method can also be used on Maps and Sets.


JavaScript forEach

The syntax of the forEach() method is:

array.forEach(function(currentValue, index, arr))

Here,

  • function(currentValue, index, arr) - a function to be run for each element of an array
  • currentValue - the value of an array
  • index (optional) - the index of the current element

arr (optional) - the array of the current elements


forEach with Arrays

The forEach() method is used to iterate over an array. For example,

Output

John
Sara
Jack

In the above program, the forEach() method takes myFunction() function that displays each element of a students array.


Updating the Array Elements

As we have seen in the above example, the forEach() method is used to iterate over an array, it is quite simple to update the array elements. For example,

Output

["Hello John", "Hello Sara", "Hello Jack"]

forEach with Arrow Function

You can use the arrow function with the forEach() method to write a program. For example,

Output

John
Sara
Jack

for loop to forEach()

Here is an example of how we can write a program with for loop and with forEach().

Using for loop

Output

["item1", "item2", "item3"]

Using forEach()


for...of with Sets

You can iterate through the Set elements using the forEach() method. For example,

Output

1
2
3

forEach with Maps

You can iterate through the Map elements using the forEach() method. For example,

Output

name- Jack
age- 27