-1

I got this code which always gave the same result:

var number = 0;
function a(){
    number++; //outside return function
    return function(){
        return number;
    };
}
var b = a(); //outside loop
for(i=0;i<10;i++){
    console.log("loop: "+(i+1)+" :"+b());
}

I found this solution (1):

var number = 0;
function a(){
    number++; //outside return function
    return function(){
        return number;
    };
}
for(i=0;i<10;i++){
    var b = a(); //inside loop
    console.log("loop: "+(i+1)+" :"+b());
}

And apparently I should've gotten the "correct" solution (2):

var number = 0;
function a(){
    return function(){
        number++; //inside return function
        return number;
    };
}
var b = a(); //outside loop
for(i=0;i<10;i++){
    console.log("loop: "+(i+1)+" :"+b());
}

In solution 1: I thought that by putting var b in the for-loop, it would "refresh" the var number with every loop, and it did because every loop a 1 is added.

In solution 2: I don't see why number++ should be added to the return function to get it looped. I.m.o. the whole a() function is run through just like in the original question and not only the code in its return method? Obviously not, why?

9duust
  • 33
  • 2
  • You might have a look into [variable scope in JavaScript](http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – mfeineis May 12 '15 at 09:45
  • Can't quite understand what you're asking. The second solution is better because you're not recreating the whole returnable function again on each iteration. – Etheryte May 12 '15 at 09:55

3 Answers3

2

In the first version a() is only called once, so number++ is only called once. In the second version you call a() with every iteration so number++ is called on every iteration. So in the first version b is always the same function and in the second you get a new one every time you call a().

mfeineis
  • 2,607
  • 19
  • 22
0

In (2) the execution of function a returns a function. Each time you execute this function, 1 is added to the global variable number.

It is the same as when you would have written:

function b() {
  number++;
  return number;
}
0

The problem in your initial situation is that you only increment the number once by calling a() once, and then it returns a function which just returns the number. Any time you call b() it will return the number which will always be 1.

In the first solution you call a() in every iteration, which will increment the number. The function b will then return the number that is incremented by a.

In the second solution you basically let a generate the function once, and then every iteration b() is called which both updates and returns the number value.

I hope this clarifies the problems your having.

Thomas Withaar
  • 165
  • 1
  • 1
  • 9