JavaScript Array forEach() Method
The JavaScript array.forEach() method allows you to execute the passed function once for each element in the array in ascending index order. The function will not be called on elements added to the array after it was called. The callback function passed as a parameter to the forEach() method will not be called for removed or missing array elements. However, it will be called for elements that have the value undefined.
Where:
- callback: a callback function will be executed once for each element in the array. If something that is not a function is passed as a method parameter, then a TypeError exception will be raised.
- thisValue (optional): an object that can be referenced by the "this" keyword inside the function. If thisValue parameter is not passed, "this" will be "undefined"
JavaScript Array forEach Method Examples
The following are examples of iterating over an array in JavaScript using forEach() method with a detailed description:
Calculating the sum of array elements using forEach()
Below is an example of how to calculate the sum of an array items using forEach() in JavaScript:
Iterating over the elements of an array containing objects
Below is an example of iterating over the elements of an array containing objects using forEach() in JavaScript:
Getting the index of an element when using forEach()
The index is passed as the second argument to the callback function when using the forEach() array method. Below is an example of how to get the index of an array element using forEach() in JavaScript: