I was pretty sure I understood scope, but this example is making me scratch my head.
var printNumTwo;
for (var i = 0; i < 3; i++) {
if (i === 2) {
printNumTwo = function() {
return i;
};
}
}
console.log(printNumTwo());
The console.log line returns “3” instead of “2”. I can’t really describe why that’s happening yet because in my brain I see the for loop running until i is equal to 2.
I think what I’m not completely sure about is the “printNumTwo = function…” portion.
Anyone care to explain what I’m missing? I can usually throw in a debugger or a console.log and start to understand what’s going on, but not quite sure this time.
The confusion arises from the fact that variables declared with var are globally scoped. Although your loops stops at i==2, the value of i is actually still incremented till 3 at which point the condition i < 3 becomes false and so the loop exits.
The i variable having been declared with var keyword will be equal to 3 at the time you reach console.log(printNumTwo()) because again the i is globally scoped with var and so effects the last increment globally.
To avoid this behavior, consider using the let keyword to declare variables as it is block scoped.
Yes, this is true. Another option is to assign i to a temporary variable within the if statement and return the temporary variable within the anonymous function.
var printNumTwo;
for (var i = 0; i < 3; i++) {
if (i === 2) {
var temp = i; // assigns 2 to temp
printNumTwo = function() {
return temp;
};
}
}
console.log(printNumTwo()); // 2
Using let to create the block scope is preferred but just wanted to show another option here.