Home >>JavaScript Array Reference >JavaScript Array forEach() Method

JavaScript Array forEach() Method

JavaScript Array forEach() Method

JavaScript array forEach() method is used to call the function once for each element in the array. Basically, this can be done by using for, while or do-while loops.

Syntax:
array.forEach( callback, thisObject )

Parameter Values

Parameter Description
function(currentValue, index, arr) It required to be run a function for each element in the array.
Function arguments:
Argument Description
currentValue It Required the current value of the element
index It is used for the array index of the current element and it is Optional
arr It is Optional and is used for the array object the current element belongs to
thisValue It is Optional and is used for a value passed to the function to be used as its "this" value. The value "undefined" will be passed as its "this" value, if this parameter is empty.

Browser Support

Method Chrome Edge Firefox Safari Opera
forEach() Yes 9.0 1.5 Yes Yes
Here is an example of JavaScript array forEach() Method:
<!DOCTYPE html>
<html>
<body>
<p id="arrayforeach"></p>
<script>
var countNum = ["Ram", "Shyam", "Geeta"];
countNum.forEach(myFunction);
function myFunction(item, index) {
  document.getElementById("arrayforeach").innerHTML += index + ":" + item + "<br>"; 
}
</script>
</body>
</html>
Output:

Example 2:
<!DOCTYPE html>
<html>
<body>
<script>
var arr = ['HTML', 'CSS', 'BOOTSTRAP'];
arr.forEach(function(fetch) {
  document.writeln(fetch);
});
</script>
</body>
</html>
Output: