DEV Community

Cover image for Performance Comparison of Javascript For Loop and Reduce Method for Array Manipulation
Paul Ikenna
Paul Ikenna

Posted on

Performance Comparison of Javascript For Loop and Reduce Method for Array Manipulation

For some time, I have been working with Data structures in javascript, Array to be precise. As an intermediate developer, I have gotten used to using for and for of loop to iterate the elements in my array, especially when I want to perform simple Arithmetic in my application .

So, I decided to explore further and try something new. In the process I realized that i can easily iterate my arrays and perform easily with some array methods (properties with function values).

These methods, include:

  1. map() method,
  2. filter() method, 3.find() method,
  3. reduce() method,.

All these new found methods have given me an advantage to do better with Data Structure (Array). For performing simple arithmetic, i will be demonstrating the reduce method.

Here is an illustration that demonstrates what I'm talking about.

Using a for of loop to perform simple arithmetic (to Sum the element in my array).
E.g

const newArray = [1,2,3,4,5]
let sum = 0;
for(const mov of newArray){
sum += mov;
}
console.log(sum);

This will give us the sum of all the elements in the array. Now let me perform the same task with reduce method;

const newArray = [1,2,3,4,5]
let sumArray = newArray.reduce(function(accum, curEl){
return accum += curtEl;
},0)

console.log(sumArray);

The reduce method takes in two arguments, first a function and second, an initial value of the accumulator. The accumulator is first parameter of the function followed by other paraments (the current array, the index, and the entire array)

Eg: reduce(function(accumulator, current Array, Index, Whole Array){}, initialValue)
With this accumulator, there is no need for the global scoped variable (sum), the entire calculation is done in the reduce method.

Top comments (0)