2

I suppose this is a newbie question, but I can't seem to figure it out. I have this code, from eloquent javascript, about the reduce function:

function forEach ( info, func ) {
    for ( i = 0; i < info.length; i++) {
        func(info[i]);
    }
}

function reduce (combine, base, array) {
    forEach(array, function(elem) {
        base = combine(base, elem);
        console.log("The base is: " + base);
    });
    return base;
}

function countZeroes(array) {
  function counter(total, element) {
    console.log("The total is: " + total);
    return total + (element === 0 ? 1 : 0);

  }
  return reduce(counter, 0, array);
}

What I can not figure out is, how is the number of zeroes stored in total through each call of the function? Why does it keep a running tab, instead of getting wiped out each time?

Marcin
  • 48,559
  • 18
  • 128
  • 201
wsnader80
  • 23
  • 3
  • Would you please clarify the question. What do you expect would get 'wiped out' each time? – seanmcl Aug 27 '13 at 18:01
  • The existing value is passed to the function (`counter`) via the `total` parameter and the function *adds* to the existing counter: `total + (element === 0 ? 1 : 0)`. – Felix Kling Aug 27 '13 at 18:02
  • 2
    Looks like Marcin nailed it. But a warning: your `i` in `forEach` is leaking to the global scope, you should be using `for (var i = 0; ...`. – bfavaretto Aug 27 '13 at 18:04
  • You're gamiliar with [how closures work](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work)? The `function(elem){…}` passed to `forEach` is one, and it closes over the common `base` variable. – Bergi Aug 27 '13 at 19:19

1 Answers1

2

The structure of reduce is that it applies a function f which takes two operands - here called element and total to a sequence. element is the next unprocessed item in the sequence (array); total is the result of the previous call to f.

Conceptually reduce(f, 0, [1,2,3]) expands to f(3,f(2,f(1,0).

Now, to answer your question: the running total is stored between invocations of counter in the variable base inside reduce.

Marcin
  • 48,559
  • 18
  • 128
  • 201