1

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++) {

}
Community
  • 1
  • 1
Moon
  • 22,195
  • 68
  • 188
  • 269
  • Similar to: [JavaScript variables declare outside or inside loop?](http://stackoverflow.com/questions/3684923/javascript-variables-declare-outside-or-inside-loop) – Brandon Boone Sep 27 '12 at 23:24
  • Na, it's just personal style. Some prefer to make the variable hoisting explicit by declaring everything at the beginning at the code. – Bergi Sep 27 '12 at 23:28

3 Answers3

2

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/

var i = 'global'; 

function test(){
    alert(i);   
    for(var i = 0; i < 10; i++){
     //do something   
    }
}
test(); 

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/

var i = 'global'; 

function test(){
    var i; 
    alert(i);   
    for(i = 0; i < 10; i++){
     //do something   
    }
}
test(); 

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. ​

Brandon Boone
  • 16,281
  • 4
  • 73
  • 100
1

No significant differences between the two -- purely a matter of opinion.

Nathan
  • 1,700
  • 12
  • 15
1
  1. it's the same
  2. It's done because in JS, the practice is to ensure that vars are declared in one spot, at the top of your function. Expressly because there is no block-scoping, and because of potential scope-chain resolution errors.
    The error wouldn't come from declaring var, but rather, forgetting to, and relying on block-scope to have your back (which it doesn't, because it doesn't exist).
Norguard
  • 26,167
  • 5
  • 41
  • 49