forEach() in JavaScript
May 7, 2022
Concise explanation of forEach() method in Js
- Iterates through an array.
- Runs a callback function on each value in the array.
- Returns undefined.
Note: forEach always returns undefined.
How does it work?
Parameters:
- Callback Function: Function to execute on each element. It is called with the following arguments:
- Value: Current element being processed in the array.
- Index: index of the element in the array.
- Array: The complete array on which forEach method is called.
- thisArg: Value to use as this when executing the callback function.
Note: In the callback function we don’t always have to use the three parameters (Value, Index, Array), Use whichever ones you need, just remember the order is important.
Note: thisArg parameter is optional too.
Examples:
- Given an array, print all the values in the console using forEach().
2. Return the sum of all elements in the array using forEach().