What is the purpose of the var keyword and when should I use it (or omit it)?
If you're in the global scope then there's not much difference. Read Kangax's answer for explanation
If you're in a function then var
will create a local variable, "no var" will look up the scope chain until it finds the variable or hits the global scope (at which point it will create it):
// These are both globals
var foo = 1;
bar = 2;
function()
{
var foo = 1; // Local
bar = 2; // Global
// Execute an anonymous function
(function()
{
var wibble = 1; // Local
foo = 2; // Inherits from scope above (creating a closure)
moo = 3; // Global
}())
}
If you're not doing an assignment then you need to use var
:
var x; // Declare x
There's a difference.
var x = 1
declares variable x
in current scope (aka execution context). If the declaration appears in a function - a local variable is declared; if it's in global scope - a global variable is declared.
x = 1
, on the other hand, is merely a property assignment. It first tries to resolve x
against scope chain. If it finds it anywhere in that scope chain, it performs assignment; if it doesn't find x
, only then does it creates x
property on a global object (which is a top level object in a scope chain).
Now, notice that it doesn't declare a global variable, it creates a global property.
The difference between the two is subtle and might be confusing unless you understand that variable declarations also create properties (only on a Variable Object) and that every property in Javascript (well, ECMAScript) have certain flags that describe their properties - ReadOnly, DontEnum and DontDelete.
Since variable declaration creates property with the DontDelete flag, the difference between var x = 1
and x = 1
(when executed in global scope) is that the former one - variable declaration - creates the DontDelete'able property, and latter one doesn't. As a consequence, the property created via this implicit assignment can then be deleted from the global object, and the former one - the one created via variable declaration - cannot be deleted.
But this is just theory of course, and in practice there are even more differences between the two, due to various bugs in implementations (such as those from IE).
Hope it all makes sense : )
[Update 2010/12/16]
In ES5 (ECMAScript 5; recently standardized, 5th edition of the language) there's a so-called "strict mode" — an opt-in language mode, which slightly changes the behavior of undeclared assignments. In strict mode, assignment to an undeclared identifier is a ReferenceError. The rationale for this was to catch accidental assignments, preventing creation of undesired global properties. Some of the newer browsers have already started rolling support for strict mode. See, for example, my compat table.
Saying it's the difference between "local and global" isn't entirely accurate.
It might be better to think of it as the difference between "local and nearest". The nearest can surely be global, but that won't always be the case.
/* global scope */
var local = true;
var global = true;
function outer() {
/* local scope */
var local = true;
var global = false;
/* nearest scope = outer */
local = !global;
function inner() {
/* nearest scope = outer */
local = false;
global = false;
/* nearest scope = undefined */
/* defaults to defining a global */
public = global;
}
}
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 declaresvar
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 withoutvar
- Always declare
var
explicitly because it's good practice