Thoughts on Array.prototype.reduce()

Parsing the meanings of “current” and “previous”

The reduce method of Javascript arrays has been a bit of a sore point for me, but I finally realized today that it’s partially a nomenclature problem: I was mixing up the meanings of “current” and “previous”.

To me, “previous value” and “current value” are misnomers. “Previous value” seems to indicate ‘the element at the previous index’. But it’s not — it actually refers to the result of the previous operation. To me, a better way to describe this concept would be accumulator, running tally, or subtotal.

Conversely, “current value” to me seems to imply a running tally. But it’s not — it’s just the value at the current index (i.e. arr[i] where i is the current index in array arr).

To think about this sequentially in an array of four elements:

  • ‘Zeroth’ iteration: Previous value comes from second parameter of reduce function, if present. Current value is the value at the current index (i = 0)
  • First iteration: Previous value is the result of the operation in the zeroth iteration. Current value is the value at the current index (i = 1)
  • Second iteration: Previous value is the result from the first iteration. Current value is the value at the current index (i = 2)
  • Third iteration: Previous value is the result from the second iteration. Current value is the value at the current index (i = 3)

I made the sketch below to try to solidify this concept. Now I just have to remind myself to stop looking at the wording in the MDN docs…. :-)

My cheat sheet for Array.prototype.reduce()


Originally published at www.dorothy.codes on January 10, 2016.

Like what you read? Give Dorothy M a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.