forEach() JavaScript Array Method – Explained with Examples
Whenever you use forEach() on an array, the method invokes its function argument once for each item of the calling array.
Syntax of the forEach()
Method
forEach()
accepts two arguments. Here is the syntax:
Argument 1: callback
A function is the first argument accepted by the forEach()
method. It is a required argument containing the code you want the computer to invoke for each item of the calling array.
Keep in mind that forEach()
’s function argument accepts three parameters: currentItem
, index
, and an array
.
Parameter 1: currentItem
The currentItem
parameter is required. It represents the current calling array’s item the computer is currently processing.
Parameter 2: index
The index
parameter is optional. It represents the index number of the item the computer is currently processing.
Parameter 3: array
The array
parameter is also optional. It represents the calling array.
Argument 2: thisValue
A thisValue
is the second argument accepted by the forEach()
method. It is an optional argument representing the value you want to use as the function argument’s this
value.
Suppose you do not provide a second argument. In that case, the computer will use undefined
as the callback function’s this
value.
Example 1: forEach()
without a thisValue
Argument
Here is an example of the forEach()
method without a thisValue
argument:
In the snippet above, we executed the forEach()
method’s function argument for each item inside the myName
array.
Example 2: forEach()
with a thisValue
Argument
Here is an example of the forEach()
method with a thisValue
argument:
In the snippet above, we executed the forEach()
method’s function argument for each item inside the myName
array. We also passed "Mr."
as mergeName
’s this
value.
forEach()
vs. map()
– What’s the Difference?
JavaScript’s forEach()
and map()
methods work similarly. The main differences between the two are:
map()
creates a new array. WhereasforEach()
does not create an array.map()
automatically puts its return values in its newly created array. However,forEach()
does not automatically put values in an array.