Just a quick question about the scoping of JavaScript variables.
Why does the alert()
function print the value of i
instead of returning undefined
?
$(document).ready(function () { for(var i = 0; i < 10; i += 1){ } alert("What is 'i'? " + i); });
I'm fairly new to JS, and in nearly all other languages I've dabbled, a declaration in the scope of the for loop would contain the value to that said loop, but not in this case, why?
i.e. What is 'i'? 10'
is printed.
In C/C++, the scope of a variable declared in a for or while loop (or any other bracketed block, for that matter) is from the open bracket to the close bracket.
Typically used to initialize a counter variable. This expression may optionally declare new variables with the var keyword. These variables are not local to the loop, i.e. they are in the same scope the for loop is in. The result of this expression is discarded. Follow this answer to receive notifications.
You can see the same behavior while using let if you've already declared the variable before using it in your for loop. Now it would behave the same way as the var for loop did. var is function scoped (in layman terms globally scoped) i.e. value declared using var is available throughout the program.
According to MDN using let in the for loop like that should bind the variable in the scope of the loop's body. Things work as I'd expect them when I use a temporary variable inside the block.
See the MDN for the "initialization parameters" of a for
-loop:
An expression (including assignment expressions) or variable declaration. Typically used to initialize a counter variable. This expression may optionally declare new variables with the var keyword. These variables are not local to the loop, i.e. they are in the same scope the for loop is in. The result of this expression is discarded.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With