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?

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

Leave a Comment