First of all, it's generally bad practice to use code outside of functions. If nothing else, wrap your code in anonymous functions:
(function(){
// code
})();
As for what effect var has, it "declares" a variable:
var foo;
alert(foo); // undefined;
vs:
alert(foo); // error: foo is not defined
The reason for this is that the above code is functionally identical to:
alert(window.foo);
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 var
is that all declarations are pulled to the top of the script, so this will work as well:
alert(foo); // undefined
var foo;
You will also have access to your variable in the window
object (though you will also have this by setting the variable without var, e.g. just foo=42
):
var foo;
for(var key in window){
// one of these keys will be 'foo'
}