The JavaScript forEach()
method run once for each element in an array. For example to navigate to array and perform any action on each array element. The JavaScript forEach() method is useful in this situation.
JavaScript forEach() method uses following syntax:
Advertisement
arrayName.forEach(function callback(currentValue, index, array) { // action on array element // action on array element }[, thisArg]);
JavaScript forEach() Example:
Below is the example of JavaScript forEach() method. In this example first we intialize and games array with some element. After that print each array element to console using forEach() method.
1 2 3 4 5 6 7 8 | <script type="text/javascript> var games = ["chess", "football", "teniss", "pool"]; games.forEach(function(entry) { console.log(entry); }); </script> |
Add the above code in an HTML file and access in the web browser. Now open the console in browser’s developer tool to view the results like below.