What is the purpose of the accumulator here?

This is one of the solutions to the Find the Longest Word in a String problem. I don’t understand why we use ‘longest’ in return statement since it seems to be doing nothing, I tried using only word.length and it still worked. Furthermore, why do we need Math.max since returning word.length alone will return the largest number anyway, I’m not sure how that works but it works. Can someone please clarify this?

function findLongestWordLength(s) {
  return s.split(' ')
    .reduce(function(longest, word) {
      return Math.max(longest, word.length)
    }, 0);
}```

what this does is to compare each element in the array .

Math.max Here serves the function of returning the greater of the values being compared.

This should not work or at least it didn’t work at my end
insum: The genral structure for finding the largest element in an array using reduce is

arrayName.reduce(
function(a, b) {
return Math.max(a, b);
}
)

Heres a link to useful resource on Math.max()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.