 # Reduce function

Reduce function
0

#1
``````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 ,

1. how does a function instantly knows that it first argument is an accumulator ??
2. In first iteration what’s the value of accumulator and current value (I’m assuming function(0,1))
3. 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 !!!

#2

The above code will iterate through arr. In the first iteration, a = 1, b=2 and after the return statement, a becomes 2 (the max of 1 and 2). In the 2nd iteration, a=2, b=3 and after the return statement a becomes 3 (the max of 2 and 3). There are no more iterations, because the entire array has been iterated.

``````var numbers = [0, 1, 2, 3];
var result = numbers.reduce(function(accumulator, currentValue) {
return accumulator + currentValue;
},0);

console.log(result);
``````

According to the reduce function documentation, the first argument in the callback function is the accumulator, but you can name it whatever you want (same goes for the 2nd and 3rd arguments).

In the first iteration of the 2nd example code you posted above, the accumulator value is 0, because it was set as the 2nd argument of the reduce function (not to be confused with the 2nd argument of the callback function).

If no initial value is given, then the first element is the value of the accumulator.

#3

Thank you sooo much !

Also just a quick question , in the below code snippet(longest word in string- Intermediate solution)

``````function findLongestWord(s) {
return s.split(' ')
.reduce(function(x, y) {
return Math.max(x, y.length)
}, 0);
}
``````

. I was just wondering that how does the program flow goes ?
example string: ""Hello my Name is Surya "“
when we
1.splitting the above string will look like [“Hello”] [’'my”] [“Name”] [“is”] [“Surya”]
2. Does the reduce function pass above string ? like

``````function (Hello,my)
{
return math.max (hello, 2) [::: since :::  my.length = 2]
}
``````

Here we’re not checking length of first argument (x) => hello , then how does it returns a max value ??

Could you pls explain me the program flow !! ? @RandellDawson

#4

X will always contain the length of the longest word found so far, so Math.max(x , y.length) is finding the larger of two numbers.