Javascript Array - forEach() Method

Tutorialsrack 01/10/2022 Jquery Javascript

In this article, you will learn about the javascript Array built-in method Array.prototype.forEach(). How does this method work in javascript? 


This Array.prototype.forEach() method invokes a function for each element in the calling array. And it returns undefined.

array.forEach(callback(element [, index [, array]]) [,thisParameter]);

This method takes 2 parameters as given below:

  • callback: This parameter holds the function to be called for each element of the array. This function takes the mentioned parameters as below:
    • element: This parameter holds the current element of the array.
    • Index(Optional): This parameter holds the index of the current element within the array.
    • array(Optional): This parameter holds the reference to the original array.
  • thisParameter(Optional): This parameter holds the context to be passed as this to be used while executing the callback function.

The forEach() does not change the original array. And it executes a callback once for each array element in order.

The forEach() does not execute the callback function for array empty elements.

Here are some examples of Array.prototype.forEach() method:

const arr = [1, 2, 3, , 5, 10, 8]

//Callback function which prints index and elements
function printElements(element, index) {
    console.log('Array Element ' + index + ': ' + element);

//foreach() Method


"Array Element 0: 1"
"Array Element 1: 2"
"Array Element 2: 3"
"Array Element 4: 5"
"Array Element 5: 10"
"Array Element 6: 8"


I hope this article will help you to understand the javascript Array built-in method Array.prototype.forEach()

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!

Related Posts


Recent Posts