The instruction states that this will return (3) rather than (2) because of the global ‘i’ variable. I don’t see where unless it’s referring to the previous example where ‘i’ DID end up being 3.
Won’t the loop stop at the return point, leaving i=2?
Thanks for any help.
var printNumTwo;
for (var i = 0; i < 3; i++) {
if (i === 2) {
printNumTwo = function() {
return i;
};
}
}
console.log(printNumTwo());
i
isn’t a global variable. It’s function scoped.
When you declare a variable with the var
keyword, it is declared globally, or locally if declared inside a function.
The loop isn’t returning at i=2
because that return statement is part of a function definition, not a block of code being run in the loop body.
That one variable i
is function scoped, and it gets increased to 3
before the loop finishes, so that’s the value of i
the function printNumTwo
has to use.