Reduce Function/ Higher Order Function

When “reducer” is taking in the function “(acc, curr) => acc + curr” , how is “acc = reducer(acc, arr[i]);” executed? Is acc adding 0 + 1 = 1 + 2 = 3 + 3 = 6?

const reduce = (reducer, initial, arr) => {
  // shared stuff
  let acc = initial;
  for (let i = 0, { length } = arr; i < length; i++) {
    // unique stuff in reducer() call
    acc = reducer(acc, arr[i]);
  // more shared stuff
  return acc;
reduce((acc, curr) => acc + curr, 0, [1,2,3]); // 6

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.


So, as I understand this, you are trying to write your own implementation of the *reduce( method - great, that’s an excellent way to understand what the prototype methods are doing and great coding practice.

how is “acc = reducer(acc, arr[i]);" executed?

I guess I don’t understand the question. Let me step through the steps here.

  1. const reduce ... defines that function but doesn’t execute it.
  2. reduce((acc, curr) => acc + curr, 0, [1,2,3]); executes it and sends it three parameters: a function, a number, and an array.
  3. let acc = initial; starts the acc out as the number you passed in (0).
    4, for (let i = 0, { length } = arr; i < length; i++) { loops through the array you sent in ([1,2,3], three values so it will loop three times).
  4. acc = reducer(acc, arr[i]); will call the function you passed in ((acc, curr) => acc + curr) with each of those values and save it into the local acc. What does that function do? Whatever you tell it to. But in the last line, the function you passed in will add them.

First of all, I don’t know if this is confusing you, but the acc in your reduce function is not the same as the acc in the anonymous function you are passing in. Yes, they essentially are, but that’s just because of how you’re mapping the parameters (completely logically). Just to keep things clear, maybe change acc on the last line to sum. I don’t know if this will help or hurt your understanding.

Other than that, I’d put in a bunch of console.log statements so you can observe what is happening.

Don’t get frustrated, reduce is one of the weirder functions. It’s pretty cool and powerful, but can be weird to understand. I literally had a senior developer last week call me to ask me how the reduce function I used worked, so don’t feel frustrated. It’s a weird little function, but it’s worth it.

1 Like

Thank you! I think I’m understanding now how reducer is working.