Vadimster
Vadimster

Reputation: 119

Clicks counter (through a closure) does not increment

Looks like for some reason my code cannot keep track of a local variable i being incremented and it always return its initial value 0.

Here is JSFiddle where I played around http://jsfiddle.net/ou2uxwn5/20/

var counter = function(){
var i = 0;
console.log(i);
return function(){
    i++;
    return i;
   };
};

Not sure if garbage collector eats it up, though behavior is the same with var calls being defined too (I would expect this to create reference and not to throw local variable i into trash bin).

What is wrong with the code and why?

Upvotes: 0

Views: 348

Answers (2)

G Roy
G Roy

Reputation: 166

You should execute the first function immediately to avoid any confusion down the line. This will return a new function and assign it to counter.

var counter = (function(){
    var i = 0;
    console.log(i);
    return function(){
        i++;
        return i;
    };
})(); // logs 0 in the console

Calls to counter() will increment i and return it's value.

console.log(counter()); // logs 1 in the console
console.log(counter()); // logs 2 in the console

I suggest you read about closures to get a better understanding of how they work. Here is a good place to start.

Upvotes: 1

Vadimster
Vadimster

Reputation: 119

problem solved:

1) should call "calls()" instead of "counter()" 2) moved console.log(i) into return statement.

Upvotes: 0

Related Questions