Coder Perfect

What is the purpose of the var keyword and when should I use it (or omit it)?


What is the purpose of the var keyword in JavaScript, and how does it vary from the other keywords?

var someNumber = 2;
var someFunction = function() { doSomething; }
var someObject = { }
var someObject.someProperty = 5;


someNumber = 2;
someFunction = function() { doSomething; }
someObject = { }
someObject.someProperty = 5;


When would you use each one, and why/what does each one accomplish?

Asked by Alex

Solution #1

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, var creates a local variable, whereas “no var” searches the scope chain until it finds the variable or reaches the global scope (at which point it creates it):

// These are both globals
var foo = 1;
bar = 2;

    var foo = 1; // Local
    bar = 2;     // Global

    // Execute an anonymous function
        var wibble = 1; // Local
        foo = 2; // Inherits from scope above (creating a closure)
        moo = 3; // Global

You must use var: if you are not working on an assignment.

var x; // Declare x

Answered by Greg

Solution #2

There’s a difference.

Variable x is declared in the current scope by var x = 1. (aka execution context). If the declaration appears in a function, it declares a local variable; if it appears in global scope, it declares a global variable.

On the other hand, x = 1 is just a property assignment. It tries to resolve x against the scope chain first. It conducts assignment if it finds it anywhere in that scope chain; if it doesn’t find x, it constructs x property on a global object (which is a top level object in a scope chain).

It’s important to note that instead of declaring a global variable, it generates a global property.

The distinction is minor and may be perplexing unless you realize that variable declarations also create properties (on a Variable Object) and that every property in Javascript (well, ECMAScript) has certain flags that describe its 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 result, the property established via implicit assignment can be removed from the global object, while the property created via variable declaration cannot be removed.

But, of course, this is only theory, and there are many more disparities between the two in practice due to numerous implementation issues (such as those from IE).

I hope everything makes sense:)

[Update 2010/12/16]

There is a so-called “strict mode” — an opt-in language mode in ES5 (ECMAScript 5; recently standardized, 5th version of the language) that somewhat alters the behavior of undeclared assignments. Assignment to an undefined identifier causes a ReferenceError in strict mode. This was done to catch unintentional assignments and prevent the establishment of unwanted global properties. Support for strict mode is already being rolled out in some of the newer browsers. Take a look at my compat table, for example.

Answered by kangax

Solution #3

It’s not exactly correct to say it’s the difference between “local and global.”

It’s easier to conceive of it as the distinction between “local” and “nearest.” Although the closest may be worldwide, this is not necessarily 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;

Answered by Jonathan Lonowski

Solution #4

When Javascript is run in a browser, it surrounds all of your code with a with statement, such as this:

with (window) {
    //Your code


There is no difference between declaring var inside window and not declaring it at all because var declares a variable in the current scope.

When you’re not exactly inside the window, such as inside a function or a block, the difference becomes apparent.

You can use var to hide foreign variables with the same name. You can imitate a “private” variable this way, but that’s a different matter.

Always use var as a rule of thumb, because otherwise you risk introducing subtle flaws.

EDIT: In light of the feedback I’ve received, I’d want to stress the following:

Answered by kentaromiura

Solution #5

To declare variables, always use the var keyword. Why? Although good coding technique should be sufficient, skipping it implies it is stated in the global scope (a variable like this is called an “implied” global). According to the Apple JavaScript Coding Guidelines, Douglas Crockford advises against using implied globals.

Answered by Steve Harrison

Post is based on