JavaScript loop variable scope

BlackBox :

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.

insertusernamehere :

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related