What does the Reduce() JavaScript function do?

I found a very useful function reduce(), and I’m using it, but I’m not sure if I understand it properly. Can anyone help me to understand this function?

Example:

var arr = [ 1, 2, 3, 4, 5, 6 ];
arr.reduce(function(p,n){
    return p + n;
}, 0);
// Output 21

This is my understanding: Reduce() loop through every element of the array and returning previous + current value. Ex. 0 + 1, 1 + 2 etc. In this case this function will return:

[0] - return 1
[1] - return 3
[2] - return 5
[3] - return 7
[4] - return 9
[5] - return 11

What next? Why does it give the result 21?

3 thoughts on “What does the Reduce() JavaScript function do?”

  1. Taken from here, arr.reduce() will reduce the array to a value, specified by the callback. In your case, it will basically sum the elements of the array.
    Steps:

    • Call function on 0,1 ( 0 is the initial value passed to .reduce() as the second argument. Return sum od 0 and 1, which is 1.
    • Call function on previous result ( which is 1 ) and next array element. This returns sum of 1 and 2, which is 3
    • Repeat until last element, which will sum up to 21
    Reply
  2. reduce() method has two parameters: a callback function that is called for every element in the array and an initial value.

    The callback function also has two parameters: an accumulator value and the current value.

    The flow for your array ([1, 2, 3, 4, 5, 6]) is like this:

    1. return 0 + 1 // 0 is the accumulator which the first time takes the initial value, 1 is the current value. The result of this becomes the accumulator for the next call, and so on..
    2. return 1 + 2 // 1 - accumulator, 2 - current value
    3. return 3 + 3 // 3 - accumulator, 3 - current value, etc...
    4. return 6 + 4
    5. return 10 + 5
    6. return 15 + 6
    

    And when reached to the end of the array, return the accumulator, which here is 21

    Reply
  3. To get a better understanding of how reduce works, use the following sum(a,b) function which logs a text like a+b=c for each operation it performs.

    function sum(a,b) { 
      const c = a + b;
      console.log(`${a} + ${b} => ${c}`)
      return c;
    }
    
    const arr = [1,2,4,8];
    const result = arr.reduce(sum);
    console.log(`result=${result}`)

    This prints 1+2=>3, 3+4=>7, 7+8=>15 and finally result=15.

    Finally, there are 2 corner cases:

    • 0 elements in the array –> throws an error.
    • just 1 element –> just returns the element.
    Reply

Leave a Comment