JavaScript Array forEach
JavaScript Array forEach() is used to execute a given function for each element in the Array.
In this tutorial, we shall learn the syntax and usage of forEach with Examples.
Syntax
The syntax of forEach() function is
arr.forEach(function callbackFun(currentValue[, index[, array]]) { //set of statements }[, thisArg]);
where
Example
In the following example, we take an array, and iterate over the elements using forEach() method.
index.html
<!doctype html> <html> <body> <h1>JavaScript - forEach Example</h1> <p id="message"></p> <script> <!-- your JavaScript goes here --> var msg=''; var names = ['Arjun', 'Akhil', 'Varma']; names.forEach(function printing(element, index, names){ msg += index + ' : ' + element + '<br>'; }); document.getElementById("message").innerHTML = msg; </script> </body> </html>
Conclusion
In this JavaScript Tutorial, we have learnt to use Array.forEach() method to apply a function for each element of the array.