var arr = [1,2,3];
var max = arr.reduce(function(a, b) {
return Math.max(a, b);
});
I’ve been going through MDN docs REDUCE function, In the above code snippet I was just wondering what does function(a,b) do. How it works will it go through like
function (1,2)
{
}
function(2,3)
{
}
function(3,1)
{
}
Also I found one more example which sums up all the elements in the array
var numbers = [0, 1, 2, 3];
var result = numbers.reduce(function(accumulator, currentValue) {
return accumulator + currentValue;
},0);
console.log(result);
So in the above example ,
- how does a function instantly knows that it first argument is an accumulator ??
- In first iteration what’s the value of accumulator and current value (I’m assuming function(0,1))
- What happens if I don’t give the initial value (here it is 0) . Is this initial value is something which will be stored into the accumulator in first iteration ??
Could someone pls help me in understanding this function ???
Thanks !!!