Possible Duplicate:
JavaScript variables declare outside or inside loop?
So..I’ve seen many articles saying that we should use the following style.
var i;
for(i=0;i <= 10; i++) {
// do something here
}
I’ve been using the above style for while, but I just wonder if it really helps except the readability.
Isn’t it same as the following?
for(var i=0; i<=10; i++) {
}
It makes a difference if for some reason (should never be the case) you’ve declared a global variable by the same name outside the context of the function.
http://jsfiddle.net/bFRKU/
In the above example, you’ll notice that the alert returns “undefined.” This is because variable definitions are hoisted to the top of the function (no matter where they are declared within the function). So in reality, the above is interpreted as:
http://jsfiddle.net/bFRKU/1/
Thus the alert “undefined.” Ultimately, the only reason to place your variable declarations at the top of your functions is to reduce this potential confusion.