When Javascript is executed in a browser, all your code is surrounded by a with statement, like so:
with (window) {
//Your code
}
More info on with - MDN
Since var declares a variable in the current scope , there is no difference between declaring var inside window and not declaring it at all.
The difference comes when you're not directly inside the window, e.g. inside a function or inside a block.
Using var lets you hide external variables that have the same name. In this way you can simulate a "private" variable, but that's another topic.
A rule of thumb is to always use var, because otherwise you run the risk of introducing subtle bugs.
EDIT:
After the critiques I received, I would like to emphasize the following:
var declares a variable in the current scope
- The global scope is
window
- Not using
var implicitly declares var in the global scope (window)
- Declaring a variable in the global scope (window) using
var is the same as omitting it.
- Declaring a variable in scopes different from window using
var is not the same thing as declaring a variable without var
- Always declare
var explicitly because it's good practice
answered 2009-09-24T09:17:57.347