I Used To Hate Using Reduce In Javascript, And Now I Can’t Stop

I used to be vehemently against using `reduce` in Javascript. It wasn’t because I thought there was a better way, I actually think the functional programming purists and their aggressive approach to advocacy are what really turned me off. That and those who advocate for using it over a basic for loop as well.

Now, there are instances where I truly believe that filter, map and reduce should not be used. If you’re just wanting to quickly iterate over a collection of values, in many instances. a for..loop will beat all of those aforementioned methods in performance every single time. And if you’re dealing with large collections of items, you will notice.

The reduce method is great for reducing values to either a singular value or manipulating the shape of data from one form to another. If you want to flatten an array, look no further than reduce. Want to average out a bunch of numbers and return a singular value? Oh, hi there reduce.

Here is an actual snippet of code I wrote not long before writing this post:

return rows.reduce((arr, row) => {
    row.contractPayload = JSON.parse(row.contractPayload) ?? {};
    arr.push(row);
    return arr;
}, [])

I am taking a bunch of rows from an SQLlite database, iterating over them and parsing a property which is stringified JSON, parsing it into an object or empty object if it doesn’t parse properly.

If I was one of those fancy developers that used shorthand for everything, I could have used the spread operator to really condense this code down into a one liner (inside the callback), but I am far too practical and prefer writing readable verbose code in most situations.

For a long time I used to be the type of developer who would create a variable with an empty array inside of it and use a for loop to push into the array, which gives you the same result.

I instinctively find that I naturally will reach for reduce over a traditional for loop whenever possible. In instances where I notice substantial performance issues, I’ll write a loop.

The real power and value of reduce is that it negates the need for unnecessary code. I guess they call it reduce because it reduces the amount of code you need to write as well. Neat.

Leave a Reply

Your email address will not be published. Required fields are marked *