Home >>JavaScript Array Reference >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 | Description | ||||||||
---|---|---|---|---|---|---|---|---|---|
function(currentValue, index, arr) | It required to be run a function for each element in the array. Function arguments:
|
||||||||
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. |
Method | Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
forEach() | Yes | 9.0 | 1.5 | Yes | Yes |
<!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>
<!DOCTYPE html> <html> <body> <script> var arr = ['HTML', 'CSS', 'BOOTSTRAP']; arr.forEach(function(fetch) { document.writeln(fetch); }); </script> </body> </html>