Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
183
rated 0 times [  184] [ 1]  / answers: 1 / hits: 73410  / 11 Years ago, tue, august 27, 2013, 12:00:00

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.


More From » variables

 Answers
28

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.



[#76099] Monday, August 26, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lizet

Total Points: 479
Total Questions: 96
Total Answers: 113

Location: Mexico
Member since Sun, Jul 25, 2021
3 Years ago
;