1

I'm struggling with this concept. By looking at below, I don't understand when I type on the console that "counter" is equal to the following below. How does it know just to pick up this piece of the code? How does this work?

function(val) {
  count += val;
  return console.log(count);
};

The Code

var incrementer = function(initialValue) {
  var count = initialValue;

  return function(val) {
    count += val;
    return console.log(count);
  };
};

var counter = incrementer(5);

counter(3);
counter(1);
  • 1
    Think of it like, functions in JavaScript are also object, it will make it easier for you to understand this concept. just like in other languages there are private instance properties which can be accessed within that class and are linked to that specific instance.:) – LNT May 15 '14 at 05:41

3 Answers3

1

Because incrementer returns a function, this effectively means that once counter is filled with incrementer(5) it then becomes a reference to the function that is returned by incrementer this means that the counter variable looks something like this at that time:

counter = function(val) {
    count += val;
    return console.log(count);
};

To verify this:

console.log(counter);

Therefore subsequent calls to counter will increment the value of count

Note: the variable count exists within the scope of incrementer and can be accessed only because the function that counter refers to was created within that scope.

Shelby L Morris
  • 726
  • 5
  • 10
0

Incrementer is a function that returns a function. counter is equal to the return of the incrementer function which is a function that takes in a value and increments the value you initially passed in incrementer(5).

Calling incrementer(5) sets the initial state intrinsically, but returns the function that you can invoke with the counter pointer (variable) you created.

Does that explanation make sense?

var counter = incrementer(5); //initializes the "initial value" and returns a function, thus setting "counter" equal to a function.. aka function pointer

counter(3);  //invokes the function that increments the value by 3 - hence 8
shredmill
  • 283
  • 3
  • 10
0

In javascript , a function remembers the context in which it has been declared.

That the quickest way to explain closures.

So if you create a function that returns a function, the returned functions will "close" on the variables of the outer function, thus the returned function having states.

Since count has been declared in the "parent" scope of the returned function, the returned function will remember that its internal variable count refers to the variable count of incrementer .

mpm
  • 20,148
  • 7
  • 50
  • 55