Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
81
rated 0 times [  82] [ 1]  / answers: 1 / hits: 18974  / 13 Years ago, sat, july 30, 2011, 12:00:00

Possible Duplicate:

Difference between using var and not using var in JavaScript






sometime, I saw people doing this



for(var i=0; i< array.length; i++){
//bababa

}


but I also see people doing this...



for(i=0; i< array.length; i++){
//bababa

}


What is the different between two? Thank you.


More From » var

 Answers
31

The var keyword is never needed. However if you don't use it then the variable that you are declaring will be exposed in the global scope (i.e. as a property on the window object). Usually this is not what you want.



Usually you only want your variable to be visible in the current scope, and this is what var does for you. It declares the variable in the current scope only (though note that in some cases the current scope will coincide with the global scope, in which case there is no difference between using var and not using var).



When writing code, you should prefer this syntax:



for(var i=0; i< array.length; i++){
//bababa
}


Or if you must, then like this:



var i;
for(i=0; i< array.length; i++){
//bababa
}


Doing it like this:



for(i=0; i< array.length; i++){
//bababa
}


...will create a variable called i in the global scope. If someone else happened to also be using a global i variable, then you've just overwritten their variable.


[#90912] Thursday, July 28, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jimmieo

Total Points: 515
Total Questions: 102
Total Answers: 110

Location: Kazakhstan
Member since Mon, Sep 26, 2022
2 Years ago
;