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.
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 thewindow
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 usingvar
and not usingvar
).When writing code, you should prefer this syntax:
Or if you must, then like this:
Doing it like this:
...will create a variable called
i
in the global scope. If someone else happened to also be using a globali
variable, then you've just overwritten their variable.technically, you never HAVE to use it, javascript will just go merrily on its way--using your variables even if you dont declare them ahead of time.
but, in practice you should always use it when you are declaring a variable. it will make your code more readable and help you to avoid confusion, especially if you are using variables with the same name and different scope...