First of all, it is generally bad practice to use code outside functions. If nothing else, wrap your code with anonymous functions:
(function(){
})();
As for the var effect, it "declares" a variable:
var foo;
alert(foo);
against
alert(foo); // error: foo is not defined
The reason for this is that the code above is functionally identical:
alert(window.foo);
var, , , .
, var , script, :
alert(foo);
var foo;
window ( , var, , foo=42):
var foo;
for(var key in window){
}