Photo by Ilija Boshkov on Unsplash

Have you ever wonder how these two functions work under the hood in JavaScript? First I would like to demonstrate the built-in functions and afterwards, we will create our own reduce and reduceRight functions. Let’s get down to business!

I created a list and declared a function that adds one to each element in the list and returns a new list in each iteration, but I applied two different functions to the same list, first reduce function and second the reduceRight function. Do you know what the difference is besides the function name?

The reduce function goes from left to right and when it reaches the last element, the function is applied to the element and in the next iteration the accumulator will be returned. When the reduceRight function is used, the iteration goes from right to left and when the last element is reached the accumulator will be empty and it runs backward, so actually, the first element is the last element, is the same as reverse the list and then apply the reduce function.

Therefore the list above for the reduce function returns [5,4,3,2] and for the reduceRight function returns [2,3,4,5]. To better exemplify this we are going to build our own functions. Let’s start with reduce:

The reduce function above receives three arguments, first the list, second the accumulator and third the reduce function. For each iteration, the accumulator is built up, and it goes until it reaches the end of the list, when there is no element, the function returns the accumulator. In other words, if we want to apply reduce to a list [1,2,3,4] where the reduce function is (acc, element) => [element + 1, …acc], the iteration will be like this:

Reduce right function will be slightly different from the previous:

The reduce right function above receives the same three arguments, first the list, second the accumulator and third the reduce function. For each iteration, it goes to the next element until it reaches the end of the list and then it starts to run backward. When there is no element it returns the accumulator.

Usually, you will use the reduce function and not the reduceRight function. I hope that now it is clear to you the difference between these two functions!

Happy coding :)