DEV Community

Byte Sized
Byte Sized

Posted on • Originally published at codeburst.io

Reduce Vs For-Loop

Are you interested in more tech content? Check us out on Twitter @nspiredTech!


I was working through some JavaScript Functional Programming examples when I came across the reduce method. By definition reduce is used to iterate through an array and condense it into one value.

This caused me to wonder what was the programmatic difference between reduce and a traditional for-loop?

Here is an example of the reduce method in action:

let singleVal = array.reduce(function(previousVal, currentVal) {
  return previousVal + currentVal;
}, 0);
Enter fullscreen mode Exit fullscreen mode

The pattern above stores the return value from the reduce method. The reduce method receives a callback function with the parameters previousVal and currentVal. As the array is being iterated each elements is being added together.

Here is the same input but with a for-loop

for(let i = 0; i < array.length; i++){
  singleVal += array[i];
}
Enter fullscreen mode Exit fullscreen mode

The same result is achieved with a for-loop. For each pass, the element or array[i] in this case, is added and stored in singleVal.


So I decided to test the two algorithms and see which performed better. Here are the results from https://jsbench.me/.

Benchmark

As you can see the for-loop outperformed the reduce method.

The results from the tests showed me the performance benefits of using one over the other, however it did not explain the programmatic difference I was looking for. So I decided to keep lookingโ€ฆ

Eventually, I found the answer!

Reduce in JavaScript is the alias for Fold, a higher order function that analyzes a recursive data structure and through use of a given combining operation, recombines the results of recursively processing its constituent parts, building up a return value.

In simpler terms, the elements are combined in a way that reflects the combination with the next element, and so on until all elements are exhausted.

Folds and maps are used to transform each value of a data structure independently, and filters are used to eliminate some elements from the data structure. Using for-loops as a jack of all trades tends to obscure the actual operation the loop performs. So from a programming standpoint, reduce is more eloquent and clear in its purpose.

In summary, we are able to determine the distinctions between the two approaches are contingent upon input and the design pattern of the programmer.

Happy Coding!

Top comments (1)

Collapse
 
ky1e_s profile image
Kyle Stephens

reduce is definitely useful, as are the other higher order looping functions, e.g. filter and map