TheLemonSong
TheLemonSong

Reputation: 21

Property in Object Not Being Reset in JavaScript

I'm looking at a JavaScript exercise and the output's a little confusing.

In the code below each time 'counter' is called the value of 'i' outputted to the console increases, but in the constructor 'i' is reset to '0' at the beginning of the object's code, so should really return '1' each time 'counter' is called.

Why is 'i' not being reset to '0' each time 'counter' is called?

Thanks in advance!:)

function makeCounter() {

   var i = 0;

   return function() {
     console.log( ++i );
   };
}

var counter = makeCounter();
counter(); //Output is 1.
counter(); //Output is 2.
counter(); //Output is 3...

Upvotes: 0

Views: 118

Answers (4)

mosabbir tuhin
mosabbir tuhin

Reputation: 625

If you want to reset the counter you have to call makeCounter() again as it only returns the function that you access with counter. It is the concept of closure that only remembers the returned function.

Upvotes: 0

Ashar Dweedar
Ashar Dweedar

Reputation: 643

you are calling the same counter which have the same i variable, it shouldn't be reset because it will call var i = 0; only the time you instantiate the counter then it will keep calling ++i to increase it, if you want new value for it call a new counter :

function makeCounter() {
   var i = 0;
   return function() {
     console.log( ++i );
   };
}
var counter = makeCounter();
counter(); //Output is 1.
counter(); //Output is 2.
counter(); //Output is 3...
var second = makeCounter();
second(); //Output is 1.

Upvotes: 2

zabusa
zabusa

Reputation: 2719

i is not changed every time because you are not updating the i is is accessed via closures so the first function is called only once

to update it do like this

function makeCounter() {

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

var counter = makeCounter();
counter(); //Output is 1.
counter(); //Output is 1.

Upvotes: 4

EKW
EKW

Reputation: 2113

Remember: calling counter() doesn't call makeCounter(). It calls the function that makeCounter returns. Because the returned function doesn't reset i's value, i never gets reset.

i is only set to 0 when makeCounter is called. As that code shows, makeCounter is only called once.

Upvotes: 4

Related Questions