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?