The reduce() method executes a callback function on each element of the array, resulting in a single output value. The function operates on an accumulator, which stores the intermediate results, and a current value, representing the current element being processed.
The Accumulator and Initial Value:
- The
accumulator is a variable that stores the result of the previous function call.
- The initial value is the starting value for the accumulator, provided as the second argument to
reduce() (in this case, 0).
How reduce() operates:
- On the first invocation, the
accumulator is set to the initial value (0), and the currentValue is the first element of the array (1).
- The function
calculateSum adds the accumulator and currentValue and returns the result, which becomes the new value of the accumulator.
Iterative Process:
-
For each subsequent element in the array, the accumulator holds the sum so far, and currentValue is the next element in the array.
| Iteration | accumulator | currentValue | Returned Value |
|---|
| 1 | 0 | 1 | 1 |
| 2 | 1 | 2 | 3 |
| 3 | 3 | 3 | 6 |
| 4 | 6 | 4 | 10 |
| 5 | 10 | 5 | 15 |
-
The final value returned by reduce() is 15.
Arguments for the Callback Function
The function passed as the first argument to reduce() can accept four parameters:
- Accumulator: Holds the value returned by the previous function call (or the initial value for the first call).
- Current Value: The current element being processed in the array.
- Current Index (optional): The index of the current element.
- Original Array (optional): The array
reduce() was called on.
Omitting the Initial Value
If the initial value is omitted, reduce() uses the first element of the array as the initial value and the iteration starts from the next element.
The first element (1) is used as the initial value and the second element (2) becomes the currentValue in the first invocation. After thus, the iterations proceed as described previously, starting with the second element.