A “reducer” function that takes four arguments:
- currentIndex (Optional)
- array (Optional)
Perhaps the easiest way to understand case for reduce() is to return the sum of all the elements in an array.
The reducer walks through the array element-by-element, at each step adding the current array value to the result from the previous step (this result is the running sum of all the previous steps) — until there are no more elements to add.
The reduce() method executes a reducer function for each value of an array.
reduce() returns a single value which is the function's accumulated result.
reduce() does not execute the function for empty array elements.
reduce() does not change the original array.
The reduce() method executes a callback function on each element of the array, resulting in single output value. Though the values in the arrays in the 2 case studies are the same, their return values are different. Hence, in order to avoid errors, It is always safe to provide an initial value for the reduce() method.