DEV Community

Discussion on: 3 Simple Snippets to Help You Understand Array .reduce()! 🥳

Collapse
 
harrison_codes profile image
Harrison Reid

Thanks! Lets see if I can explain this...

The const findLargest is a function that accepts two arguments. I've called these arguments currentMax and numberToCheck, but those names only really make sense in the context of that function being used as a callback in .reduce(). We could equally call those arguments firstNumber and secondNumber, so lets do that...

const findLarger = (firstNumber, secondNumber) => {
  if (secondNumber > firstNumber) {
    return secondNumber;
  }
  return firstNumber;
}

Looking at this function now, you'll see it just receives two numbers, and returns the larger of the two.

We then pass this function as the callback to .reduce():

const numbers = [ 10, 40, 4, 50, 101 ]
const largest = numbers.reduce(findLarger) 

From here, .reduce() iterates over the array (but skips the first element, as we haven't provided an initial value for reduce to use, so it uses the first array item as this initial value).

For each subsequent array item, reduce will call the findLarger() function, and will pass in two arguments. The first will be the return value from the previous call to findLarger(), or the initial value if there were no previous calls. The second will be the current array item.

So for each array item, reduce calls:

// This isn't real code, just trying to annotate where the arguments are coming from...
findLarger(<previousReturnedValue>, <currentArrayItem>)` 

Since findLarger() returns the larger of two numbers, and this returned number is then passed into the next findLarger() call, and so on, the last number that is returned once we've iterated over the full array should be the largest.

Hopefully this helps! And thanks for reading 😃