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.