DEV Community

Discussion on: I spent an entire Saturday trying to understand .reduce()

 
earthtone profile image
Tonio Hubilla

It's sometimes called fold in other languages.

Reduce is probably my favorite list operation, but it took me quite a while to really grok it and feel comfortable using it as often as I do now.

Two important things I noticed about your friend's example that helped me in the beginning are his use of an optional argument - i for the parent array's index - and his explicit assigning of an initial value - ''.

Optional arguments, like index aren't traditionally included in other implementations of reduce, and it's something specific to JavaScript's implementation on Array. I found it super useful as I was starting to learn, but eventually you build up a confidence with writing "pure" reducers.

Setting initial values for your accumulator is a great sanity guard, and communicates what type of elements your reducer can work with. For example, if you have an array that is a mix of numbers and strings, setting an initial value will remind how to "cast" or "coerce" your elements...

const unsafelyConcatenateAll = [0, 'x', 3, 'z'].reduce((a, c) => a + c.toUpperCase()) // -> TypeError: c.toUpperCase is not a function

const safelyConcatenateAll = [0, 'x', 3, 'z'].reduce((a, c) => a + String(c).toUpperCase(), '') // -> "0X3Z"

JavaScript actually sets your accumulator's initial value as the first index of the parent array if none is given. So unsafelyConcatenateAll fails because the initial value is a Number not a String. There's a ton of other useful things about explicitly setting your initial value, but in my experience the most important is that it communicates to other people (including future self) "Hey, don't try to do math on strings!" or whatever the case may be

Most of this probably doesn't mean much to you yet, but learning to love reduce was the beginning of my journey down the Functional Programming rabbit hole I'm still falling down today. If you had fun learning about reduce, map, filter and other list operations, I'd highly recommend Kyle Simpson's Functional Light JS book for a clear, no-nonsense, practical background on the theoretical stuff.

Thread Thread
 
phillipkent profile image
Phillip Kent Knight

This is a great explanation and makes perfect sense to me - my original post was mostly driven by failing to properly imagine/visualize the accumulator itself, but it's definitely helpful to have a clearer understanding of the use cases for initial value and index.