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.
After adding it is putting the sum to
baseonly. So it is getting incremented on every loop.base = combine(base, element)This statement first computes
combine(base, element)and assigns it tobase. Its not comparing0andadd(0, 1). So for the next iteration,basewould have the sum for all the previous values.EDITED
Suppose, you call
reduce(combine, 0, [10, 22, 7, 5]). Loop will be iterated asAfter computing
add(base, element),baseis set to 10. So for the next iteration, its value is 10.After computing
add(base, element),baseis set to 32. So for the next iteration, its value is 32.After computing
add(base, element),baseis set to 39. So for the next iteration, its value is 39.After computing
add(base, element),baseis set to 44. Since there are no more elements left, the answer is 44.