DEV Community

kaur0762
kaur0762

Posted on

Using Array.prototype.reduce()

The Array.prototype.reduce() method is an immutable JavaScript array iteration method that executes a callback function on each element of the array, resulting in a single output value.

Syntax

Image description

Parameters

CALLBACKFN
A “reducer” function that takes four arguments:

  1. previousValue
  2. currentValue
  3. currentIndex (Optional)
  4. array (Optional)

Explanation

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.

This is shown in the following interactive example:
Image description

Usage

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.

Conclusion

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.

Discussion (0)