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?

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:

`.reduce()`

as the second argument. Return sum od 0 and 1, which is 1.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:And when reached to the end of the array, return the accumulator, which here is 21

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.This prints

`1+2=>3`

,`3+4=>7`

,`7+8=>15`

and finally`result=15`

.Finally, there are 2 corner cases: