Possible Duplicate:
JavaScript Variable Scope
My understanding it that with in a function if I use var then I have a local variable. If I do not delcare var I now have a global variable.
But what about oustide of functions, what effect does var have?
First of all, it’s generally bad practice to use code outside of functions. If nothing else, wrap your code in anonymous functions:
As for what effect var has, it “declares” a variable:
vs:
The reason for this is that the above code is functionally identical to:
without declaring the variable with
var, you get a lookup error, the same as trying to access the property of any object that doesn’t exist.Note that one of the oddities of
varis that all declarations are pulled to the top of the script, so this will work as well:You will also have access to your variable in the
windowobject (though you will also have this by setting the variable without var, e.g. justfoo=42):