BeetleTheNeato
BeetleTheNeato

Reputation: 389

A reduce function in Javascript

I'm studying Javascript using Marijn Haverbeke's book Eloquent JavaScript and didn't understand the following example:

function reduce(combine, base, array) {
    forEach(array, function (element) {
        base = combine(base, element);
    });
    return base;
}

function add(a, b) {
    return a + b;
}

function sum(numbers) {
    return reduce(add, 0, numbers);
}

The forEach function is one he introduces earlier in the book, which is the following:

function forEach(array, action) {
    for(var i = 0; i < array.length; i++)
        action(array[i]);
}

Now, back to the reduce function, what I don't understand is why, in the sum function, 0 is passed as base to reduce. Isn't that weird? Let's say I try to run sum([1,2,3])... wouldn't it look something like 0 = add(0,1) in its first loop? I don't get it.

Upvotes: 2

Views: 699

Answers (3)

rainbowsorbet
rainbowsorbet

Reputation: 563

Remember as well that the content on the right side of the equals sign is evaluated first. So,

base = combine(base, element)

is taking the result of combine(base, element) and assigning it to the variable base (which now overwrites what base was previously assigned to).

Upvotes: 1

Shashwat
Shashwat

Reputation: 2668

After adding it is putting the sum to base only. So it is getting incremented on every loop.

base = combine(base, element)

This statement first computes combine(base, element) and assigns it to base. Its not comparing 0 and add(0, 1). So for the next iteration, base would have the sum for all the previous values.

EDITED

Suppose, you call reduce(combine, 0, [10, 22, 7, 5]). Loop will be iterated as

Iteration           base          element
1                   0             10

After computing add(base, element), base is set to 10. So for the next iteration, its value is 10.

1                   10            22

After computing add(base, element), base is set to 32. So for the next iteration, its value is 32.

1                   32            7

After computing add(base, element), base is set to 39. So for the next iteration, its value is 39.

1                   39            5

After computing add(base, element), base is set to 44. Since there are no more elements left, the answer is 44.

Upvotes: 2

Majid Laissi
Majid Laissi

Reputation: 19788

base is the variable that will contain the sum of all elements. It's normal that it starts with 0.

It's not : 0 = add(0,1)

but rather : base will contain the sum of previous value of base and 1

Upvotes: 1

Related Questions