DEV Community

Eray Kaya
Eray Kaya

Posted on • Edited on

How does reduce method works?

In this series i will try to explain how does an underrated javascript method, reduce, works and how we can use this method.

First let's take a look at how we would write this function if it wouldn't exist natively.

Reduce function follows accumulator pattern meaning that it tries to reduce the value, which we put into our function, to a single value.

It takes two parameters first one is callback function, second one is the initial value. If we define initial value, accumulator starts equal to the initial value. If not it starts as first element of the array.

function fakeReduce() {
  function reduce(callback, initialValue) {
    let accumulator;
    let start = 0;

    if(initialValue) {
      accumulator = initialValue;
   } else {
     accumulator = this[0];
     start = 1;
   }

  }
Enter fullscreen mode Exit fullscreen mode

After we need to define our callback function which takes 4 parameters: accumulator, current value, index number and array. At each for iteration callback function runs again until loop is over and our return value is accumulator.


  function fakeReduce(callback, initialValue) {
    let accumulator;
    let start = 0;
   //**this** keyword in this function scope points to array which reduce method is used on 
    if(initialValue) {
      accumulator = initialValue;
   } else {
     accumulator = this[0];
     start = 1;
   }

   for (let i = start; i < this.length; i++) {
     accumulator = callback(accumulator, this[i], i, this);
   }

   return accumulator;
  }
Enter fullscreen mode Exit fullscreen mode

Right now missing part of our function is error handling but we will not get into that. Our main goal here is to understand how does reduce method works.

In next post of this series i will show some examples how we can use reduce for more complex tasks rather than just summing up numbers of an array.

See you in next post...

Top comments (0)