forEach() Function is used to call a function as many times as that of the Array elements.
Let us say, we have a Array that contains five numbers, 5, 8, 2, 81 and 9.
And we want to call a function at each iteration.
And forEach() helps us achieve the above.
Let us see in the below example.
<html> <body> <script> function numberCheck(element) { document.write(element, "</br>") } var x = [5, 8, 2, 81, 9] x.forEach(numberCheck) </script> </body> </html>
So, we have an Array that has 5 numbers.
And we have defined a function called numberCheck(), that prints the values of the array.
function numberCheck(element) { document.write(element, "</br>") }
And we have called the above function from map() function.
var y = x.map(numberCheck)
And forEach() function iterates 5 times(i.e. The length of the array), calling numberCheck() function.
x.forEach(numberCheck)
And it prints the values of the Array
Again, let us say, we want to display the values of the array along with its indexes.
Luckily, forEach() function allows us to achieve that as well.
Let us see in the below example.
<html> <body> <script> function numberCheck(element, index) { document.write(index, " --> ", element, "</br>") } var x = [5, 8, 2, 81, 9] x.forEach(numberCheck) </script> </body> </html>
So, the first argument in the forEach() function is the actual value and the second argument is the index of it.
And accordingly, we have defined the function.
function numberCheck(element, index) { document.write(index, " --> ", element, "</br>") }
And called it from forEach(),
x.forEach(numberCheck)