Proceeding in our reduce() series, this is our third installment. In here, we'll enter the guts of the method and see how it works. But, first, a little recap of what we got so far.

You've learned that reduce() is an iteration method whose return value can be baked into whatever you want by a callback argument. This flexibility of reduce()'s makes it peculiar. And interesting. But what is happening behind the scenes to make that possible? Let's see.

To illustrate

Say we have the following array

    var arr = [1, 2, 3]

and we want to reduce it to a single Number value.

Let's first define our callback (or reducer), which we'll use to make the magic happen.

    var reducer = (acc, cur) => acc + cur

Therefore, our reduce() call on the arr array will be

    console.log(arr.reduce(reducer, 0)) // 6 from 3 iterations but predictable
    console.log(arr.reduce(reducer)) // 6 from 2 iterations but not advised

So, we went from an array [1, 2, 3] and got to the "single" number 6. How? Okay, fairly obvious, right, it's 1 + 2 + 3? Actually, what's happening is 0 + 1, then 1 + 2, and, finally 3 + 3, each for each call and compounding until it runs out of currentValue. Easy, if confused - we're getting right into it now.

How reduce() works

On our arr array, reducer is called 3 times if an ini is given, but twice if not. You're advised to always supply an initial value. Let's break it down:

    first call
        acc             0 (because ini = 0)
        cur             1 (because 1, first index, is available)
        return value    1 (because 0 + 1)
    second call
        acc             1 (previous return value)
        cur             2 (second index in array, shifts right one step)
        return value    3 (1 + 2)
    third call
        acc             3 (last return value)
        cur             3 (next index so far)
        return value    6 (3 + 3)

    And, you've run out of indexes, so no more calls.

As you can see, reduce() starts the loop by assigning a value to the accumulator acc, in this case, 0. So, the calculation asked for by the reducer callback starts from 0. And as the currentValue cur is 1 (since an initialValue was passed in), 1, that is, 0 + 1 becomes the return value of the first call.

This return value is then assigned to the acc for the next call. On this second call, the cur shifts to the next index or element or item in the array. The iteration continues until there's no more currentValue left. The value returned by reduce() is the final value of acc.

The takeaway is the reduce() "calls". You tell it where to start, what to start with, and/or based on what sort of result you want.

At this point, it's either all a lot of grammar and I've succeeded in confusing you much more or you already see how clear it is. Because as we proceed to the examples, nothing will change of how it works and you'll be opened up to its world of possibilities despite how complex some examples may be. See you in the next one.