The forEach() method executes a provided function for each array element.
Example
forEach() Syntax
The syntax of the forEach() method is:
arr.forEach(callback(currentValue), thisArg)
Here, arr is an array.
forEach() Parameters
The forEach() method takes in:
- callback - The function to execute on every array element. It takes in:
- currentValue - The current element being passed from the array.
- thisArg (optional) - Value to use as
thiswhen executing callback. By default, it isundefined.
forEach() Return Value
- Returns
undefined.
Notes:
forEach()does not change the original array.forEach()executescallbackonce for each array element in order.forEach()does not executecallbackfor array elements without values.
Example 1: Printing Contents of Array
Output
Array Element 0: 1800 Array Element 1: 2000 Array Element 2: 3000 Array Element 4: 5000 Array Element 5: 500 Array Element 6: 8000
Example 2: Using thisArg
Output
4 58 1440
Here, we can again see that forEach skips the empty element. thisArg is passed as this inside the definition of the execute method of the Counter object.
Recommended Reading: JavaScript Array map()