Array Reduce ( ) Method

Can someone explain this 0 to me? Without the "0" in the getSum, Math.round(num) will not round the numbers in the array; it will just add them.

var numbers = [15.5, 2.3, 1.1, 4.7];

function getSum(total, num) {
  return total + Math.round(num); 
function myFunctionTwo(items) {
  document.getElementById("demo2").innerHTML = numbers.reduce(getSum, 0); // this ZERO I need it explained. Is the initial value? 

This is the syntax array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

Yes, the 2nd argument passed to the reduce function is the initial value of the accumulator.

@MizoCoder First iteration of total isn’t set to zero it’s set to the first returned value which would be 15.5.

The Array.reduce() function can take an optional second parameter. If it is supplied then it is the initial value for the accumulator used in the reduce function. If it is not supplied then the first item in the array becomes the accumulator.

1 Like

@MizoCoder Good question!

Actually, in this example, the first value of the accumulator is zero since that value is supplied.

Thank you for answering my post. I was not sure if it is the initial value until I saw your answer to my question.

Thank you for explaining it to me.

Thank you for that explanation.

I was actually trying learn the reduce method myself too…so I decided to try and share. no problem.

Questions like that are good :slight_smile:

Don’t you mean the first argument is the initial value and the second argument is the current value?

Nvm., I’m thinking of the 2nd argument of the callback function…

reduce(callback(a,b,c,d), e)