views:

1499

answers:

8

What exactly is the function of the var keyword in Javascript, and what is the difference between:

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

and:

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

When would you use either one, and why/what does it do?

+32  A: 

If you're in the global scope then there's no difference.

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
Greg
Is "not really much difference" == "No Difference"?
Alex
Well, actually yes, there's difference :) Whether that difference is important is another question. See my answer further down: http://stackoverflow.com/questions/1470488/difference-between-using-var-and-not-using-var-in-javascript#answer-1471738
kangax
+1  A: 

I would say it's better to use "var" in most situations.

Local variables are always faster than the variables in global scope.

If you do not use "var" to declare a variable, the variable will be in global scope.

For more information, you can search "scope chain javascript" in Google.

Billy
+2  A: 

Without var - global variable. Strongly recommended to ALWAYS use var statement, because init global variable in local context - is evil. But, if you need this dirty trick, you should write comment at start of page:

/* global: varname1, varname2... */

Anatoliy
+3  A: 

You have to know that when javascript is executed in a browser, all your code is surrounded by a implicit

with(window){}

with keyword

now, since var declare a variable in the current scope , there are no difference in using var inside window or not using it.

The difference comes when you're not directly inside window, for example inside a function or inside a block.

Using var let you hide external variable that have the same name in this way you can simulate private variable, but that's another topic.

A rule of thumb is to always use var, because otherwise you risk to introduce subtle bugs

EDIT: After the critics I received, I would like to point out, the bottom line:

  • var declare a variable in the current scope
  • the global scope is window
  • not using var implicit declare var in the global scope(window)
  • declaring variable in global scope(window) using var, or omitting var is the same.
  • declaring variable in scopes different from window using var is not the same thing of declaring variable without var
  • always declare var explicit, is a good practice
kentaromiura
Why the downvote? I would like an explanation, please ...
kentaromiura
I didn't downvote you, but scope is probably a better word than window. You're whole explanation is a bit obtuse.
Robert Harvey
I simply call things with it's name, you want to call it "global scope", it's ok, but client-side, by convention, is the window object, that is the last element of the scope chain, that why you can call every function and every object in window without write "window."
kentaromiura
+3  A: 

Here's quite a good example of how you can get caught out from not declaring local variables with var:

<script>
one();

function one()
{
    for (i = 0;i < 10;i++)
    {
     two(i);
     alert(i);
    }
}

function two()
{
    i = 1;
}
</script>
Chris S
+8  A: 

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;
    }
}
Jonathan Lonowski
This is a very clear explanation.
kirk.burleson
+4  A: 

You should always use the var keyword to declare variables. Why? Good coding practice should be enough of a reason in itself, but declaring a variable without the var keyword means it is declared in the global scope (a variable like this is called an "implied" global). Douglas Crockford recommends never using implied globals, and according to the Apple JavaScript Coding Guidelines:

Any variable created without the var keyword is created at the global scope and is not garbage collected when the function returns (because it doesn’t go out of scope), presenting the opportunity for a memory leak.

So, in short, always declare variables using the var keyword.

Steve Harrison
+24  A: 

There's a difference.

var x = 1 declares variable x in current scope (aka execution context). If declaration appears in a function - local variable is declared; if it's in global scope - 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 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 global variable, it creates a global property.

The difference between 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 DontDelete flag, the difference between var x = 1 and x = 1 (when executed in global scope) is that former one - variable declaration - creates DontDelete'able property, and latter one doesn't. As a consequence, property created via this implicit assignment can then be deleted from the global object, and former one - the one created via variable declaration - can not be.

But this is jut theory of course, and in practice there are even more differences between two, due to various bugs in implementations (such as that from IE).

Hope it all makes sense : )

kangax
Have you got your formers and latters mixed up in the third last paragraph?
Tim Down
Yes I did Tim, thanks a bunch! Fixed it.
kangax