Vaibhav Namburi

Posted on

# Understanding the reduce method in 2 mins

A little background, my name is Vaibhav - from Five2One. Iâ€™ve been involved in JS for nearly 8-9 years now, Angular 1 days and basically helped build/train 15000+ people on Udemy. Code that serves millions of people so my job is not just to build scalable code patterns but actually care ALOT about performance.

One of the things I like doing is knowing how the tools I use are internally optimised or operate - helps me learn. So I wanted to share with people how the reduce function worked, which is often very confusing of people getting into JS, programming, or the callback paradigm.

So let's jump into it. (ps this isn't super optimised for all edge cases, because that'll dilute the principle behind explaining it, i encourage you to actually write down your version of this in the comments)

What we have is a simple forEach function, that takes in a collection/array and a callback

A simple for loop that calls a function that is passed to it with each element in the collection/array.

So a quick implementation of it is as such

So why are we doing a forEach ? Give it a second...you'll see why.

(One second later)

Okay let's look into the implementation of a reduce function, but before that - let's write down the specs of a reduce function:

• takes in a collection
• takes in a callback which is involved with the accumulated value and the current item in the collection in the iteration
• takes in an initial value

Phew, that's a few things.

Here's the quick implementation before we go into the details of what's happening

An accumulator in a reduce function is a value that holds the "total" or the condensation of whatever we're trying to get to, this can be an object, a number, a string, anything that suits the bill.

So, `accum=initialiser`, we're setting the accumulated value to the initialiser we provide to the function IF it exists that is

Then, voila, we use our forEach, to loop through the collection, except something unique is happening in the callback.

We're saying that if the `accum` is not defined, in the first run, it means if the initial value is not defined, then go ahead and assign the first value in the collection to the `accum` variable and get out of the loop, else its business as usual and involve the callback with the accumulated value as well as the current iterative value.

The callback's return value is assigned back to the accumulator, remember it's the `accumulator` its job is to continuously condense values as it treads through the collection.

And that's as simple as it gets

``````
const number = reduce([1, 2], (accum, val) => {
accum = accum + val;
return accum
}, 5)

console.log('number', number); // 8

``````

Hopefully, this helped you! :)