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

}
2
  • Similar to: JavaScript variables declare outside or inside loop? Commented Sep 27, 2012 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. Commented Sep 27, 2012 at 23:28

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.