JavaScript Array forEach()

The JavaScript array forEach() method is used to invoke the provided function once for each element of an array.

Syntax:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
array.forEach (callback (currentvalue, index, arr), thisArg)
array.forEach (callback (currentvalue, index, arr), thisArg)
array.forEach (callback (currentvalue, index, arr), thisArg)

Parameters:
callback: It represents the method to test the condition. It is required.
currentValue: It represents the array’s current element. It is required.
index: Current element index. It is optional.
arr: It represents the array on which every() method is to be invoked. It is optional.
thisArg: It is used as this keyword while executing callback. It is optional.

Example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
var a = ["GOLD","SILVER","DIAMOND","RUBY","PLATINUM"]
a.forEach(function(fetch) {
document.writeln(fetch);
});
</script>
</body>
</html>
<!DOCTYPE html> <html> <head> </head> <body> <script> var a = ["GOLD","SILVER","DIAMOND","RUBY","PLATINUM"] a.forEach(function(fetch) { document.writeln(fetch); }); </script> </body> </html>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
var a = ["GOLD","SILVER","DIAMOND","RUBY","PLATINUM"]
a.forEach(function(fetch) {
document.writeln(fetch);
});
</script>
</body>
</html>