Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

NOTE: This question was asked from the viewpoint of ECMAScript version 3 or 5. The answers might become outdated with the introduction of new features in the release of ECMAScript 6.

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?

share|improve this question
298  
To var, or not to var: that is the question: Whether 'tis nobler in the mind to suffer The slings and arrows of outrageous fortune, Or to take arms against a sea of troubles, And by opposing end them? To die: to sleep; No more; and by a sleep to say we end The heart-ache and the thousand natural shocks That flesh is heir to, 'tis a consummation Devoutly to be wish'd. To die, to sleep; To sleep: perchance to dream: ay, there's the rub; For in that sleep of death what dreams may come When we have shuffled off this mortal coil, Must give us pause: there's the respect ... –  KristoferA Sep 24 '09 at 8:56
16  
Note that you can chain var declarations like this: var x = 1, y = 2, z = 3; –  Reinis I. Sep 24 '09 at 9:43
9  
Always use var! Even in global scope, otherwise you might have problems with IE (at least version 6). I'm telling this from my own experience. –  jamolkhon Sep 25 '09 at 9:30
6  
A good reason to always use var is the following horror story: blog.meloncard.com/post/12175941935/… –  Ray Toal Nov 26 '11 at 3:12
4  
@Alfabravo no . –  ANeves Aug 16 '12 at 14:17

14 Answers 14

up vote 734 down vote accepted

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
share|improve this answer
13  
Is "not really much difference" == "No Difference"? –  Alex Sep 24 '09 at 8:56
46  
Well, actually yes, there's difference :) Whether that difference is important is another question. See my answer further down: stackoverflow.com/questions/1470488/… –  kangax Sep 25 '09 at 4:11
3  
I think that may be Alex's point, which is why he's written it using the "is equal to" operator! –  James Bedford Sep 13 '12 at 17:52
2  
It's like shooting oneself with a railgun... Forget to put a 'var' before one's variable, and end up modifying a variable somewhere in the scope chain... Try convincing a Java/C/Python/etc. developer that JavaScript is worthwhile. Ha! C/C++ pitfalls look nice by contrast. Imagine having to debug JavaScript... And some people do that, of course. And there's so much code (and not simple code, mind you) written in JavaScript... –  Albus Dumbledore Feb 24 '13 at 12:33
4  
If you're in the global scope then there's no difference. >> there is a difference which is explained in the answer below –  Maximus Sep 13 '13 at 11:39

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 : )

[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.

share|improve this answer
    
If I recall correctly, I think I once found a way to be able to delete a var-declared variable with some eval hack. If I remember the exact trick I'll post here. –  Tower Jun 30 '11 at 14:51
    
@rFactor Did you find it. –  Mageek Jun 19 '12 at 17:07
2  
@Mageek He might be taking about eval-declared variables which are deletable. I wrote a blog post about this once. –  kangax Jun 20 '12 at 11:06
    
@Mageek yes, exactly as kangax mentioned. –  Tower Jun 20 '12 at 15:03
    
Little bit out of topic, but mentioning it here for reference. "let" is very similar to "var" and is supported in Mozilla. The main difference is that the scope of a var variable is the entire enclosing function where as "let" is restricted to its block –  mac Oct 1 '12 at 11:16

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;
    }
}
share|improve this answer
7  
This is a very clear explanation. –  kirk.burleson Aug 15 '10 at 14:39
2  
Isn't the nearest scope outer where you define var global = false;? –  Snekse Apr 19 '13 at 13:33

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
share|improve this answer
1  
Why the downvote? I would like an explanation, please ... –  kentaromiura Sep 24 '09 at 14:37
1  
I didn't downvote you, but scope is probably a better word than window. You're whole explanation is a bit obtuse. –  Robert Harvey Sep 24 '09 at 23:12
3  
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 Sep 25 '09 at 5:19
1  
+1 this is a really nice explanation--i have not heard the var/no var issue framed (no pun intended) like this before. –  doug Apr 9 '12 at 23:49
    
The with keyword is not recommended to use. –  Licson Dec 31 '12 at 17:49

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.

share|improve this answer
7  
"Good coding practice" should never be sufficient reason in itself. It amounts to "some guys on the internet said this is how my code should look". That's even less valid than "my teacher said", unless one at least vaguely understands the reason behind the rule. –  cHao May 24 '13 at 4:34
    
@cHao I think good coding practice is always sufficient reason if it's a recommended best practice, which this is and by several Javascript authors. –  Chris S Jan 3 '14 at 13:58
    
@ChrisS: No, "good coding practice" is not reason in itself. The reason it's considered good practice is what matters. Unless those authors tell you why they recommend it, their recommendation should carry no weight whatsoever. If you don't agree with the reasons, then you are free to consider it bad advice. And if you follow it without ever asking why, that is how cargo cultism starts. –  cHao Jan 3 '14 at 18:16
    
@cHao He did, didn't he? :) Albeit giving the reason after saying it's a good coding practice –  Chris S Jan 3 '14 at 20:43
1  
@ChrisS: Yep. And the rest of the answer is pretty good. :) My only beef is with the statement that "Good coding practice should be enough of a reason in itself". "Good practice" in itself is not a reason at all -- on its own, it is basically just some geeks' opinion. The objective reasons behind that opinion are what's important; they allow us to see for ourselves that the geeks aren't just talking out of their asses again. :) And we should always be able to verify that (and do so!), lest we start following bad advice just because some famous author was drunk one day. –  cHao Jan 3 '14 at 21:44

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>

(i is reset at every iteration of the loop, as it's not declared locally in the for loop but globally)

share|improve this answer
    
Yikes! I can just imagine all the bugs that could be caused by that typo. –  BonsaiOak Oct 12 '14 at 20:07

another difference e.g

var a = a || [] ; // works 

while

a = a || [] ; // a is undefined error.
share|improve this answer
    
Could You explain why it works in case of variable defined with 'var' and variable not defined with var? Is variable created before evaluation of right side of assignment in case of var? –  lucek Dec 5 '13 at 13:11
4  
@Lucek because var a is hoisted to the top of the scope and set to null which declares but does not initialize the variable, then in assignment you have a reference to an undefined null variable which evaluates to false, and set the assignment to []. In the latter, you have an assignment to the property a of the property a. You can assign to a property that does not exist -- creating it on assignment, but you can't read from a property that does not exist without a getting a ReferenceError thrown at you. –  Evan Carroll Jan 20 '14 at 19:43
1  
@EvanCarroll : it gets hoisted to top of scope and gets set to undefined instead of null. –  mithunsatheesh Sep 25 '14 at 7:40

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.

share|improve this answer
    
If you declare a variable by using var keyword, it will be created at runtime so shouldnt it be slower ? Because other one is created at parsed time. –  Ryu Kaplan Aug 14 '12 at 1:12
    
@RyuKaplan - hey, is that true? I tried googling and couldn't get any info on the subject! Do you have a source authority for that assertion? Thx –  mike rodent Apr 12 '13 at 17:24

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... */

share|improve this answer

Using var is always a good idea to prevent variables from cluttering the global scope and variables from conflicting with each other, causing unwanted overwriting.

share|improve this answer

Inside a code you if you use a variable without using var, then what happens is the automatically var var_name is placed in the global scope eg:

someFunction() {
    var a = some_value; /*a has local scope and it cannot be accessed when this
    function is not active*/
    b = a; /*here it places "var b" at top of script i.e. gives b global scope or
    uses already defined global variable b */
}
share|improve this answer

this is example code I have written to understand this concept. I hop this is helpful.

var foo = 5; 
    bar = 2;     
    fooba = 3;
    // Execute an anonymous function
    function test()
    {    bar=100;
       var foo = 4; 
       var fooba=900;
        document.write(foo);//4
        document.write(bar);//100
        document.write(fooba);//900
    }
    test();
    document.write('<br/>');
    document.write('<br/>');
    document.write(foo);//5
    document.write(bar);//100
    document.write(fooba);//3
share|improve this answer
2  
The function is by no means "anonymous". In fact, it is about as visibly named as it can possibly be. –  Ingo Bürk Jan 22 '14 at 22:12

Without using "var" variables can only define when set a value. In example:

my_var;

cannot work in global scope or any other scope. It should be with value like:

my_var = "value";

On the other hand you can define a vaiable like;

var my_var;

Its value is undefined ( Its value is not null and it is not equal to null interestingly.).

share|improve this answer
    
my_var; is actually a valid expression statement. –  lexicore Nov 27 '14 at 13:23
    
It is valid statement if variable is defined before. Otherwise it throw an error "... is not defined". –  umut Nov 27 '14 at 13:31
    
It is a valid statement regardless of if a variable was defined before or not. :) A valid statement can throw an eror it does not make the statement invalid. –  lexicore Nov 27 '14 at 14:37
    
I am confused about it. What is valid statement? And can you give me an invalid statement example? –  umut Nov 27 '14 at 14:59
    
I'll have to apologize - too much ECMAScript grammar lately. my_var; is a valid expression statement. /my_var; would be a invalid statement. But as I said, this is grammar casuistics, I apologize, my comment was actually not appropriate. –  lexicore Nov 27 '14 at 15:05

Differences between declaring a variable with 'var' and without 'var' keyword:

I would like to add two words to answer the question 'Initializing' and 'assignment'

If you declare a variable with 'var' keyword it simply initialize the variable.

Example: var x=10; (initialize the variable)

If you declare a variable without 'var' keyword it will assign the value to variable name. If the variable is not intialized earlier it does the initialization of variable.

Example: x=10; (it will assign '10' to 'x')

CONSIDER THE BELOW EXAMPLES:


example 1:

var x=10; //initialize and assigns 10 to y (global scope)

function fun(){

var x=20; //initialize and assigns 10 to x (local scope)

console.log(x); //prints 20

}

console.log(x); //prints 10


example 2:

y=10; //initialize and assigns 10 to y (global scope)

function fun(){

y=20; //assign 20 to y (global scope)

console.log(y); //prints 20

}

console.log(y); //prints 20


example 3: z=10; //initialize and assigns 10 to z (global scope)

function fun(){

var z=20; //intialize and assigns 20 to z (local scope)

console.log(z); //prints 20

}

console.log(z); //prints 10

basically 'var' keyword is used to define a variable with in local scope if you use 'var' keyword the value will be available to that particular scope only.

share|improve this answer
    
Your example 2 just prints 10. –  lexicore Nov 27 '14 at 13:15
    
As well as example 3. –  lexicore Nov 27 '14 at 13:17
    
As well as example 1. –  lexicore Nov 27 '14 at 13:18
    
You never run your function. –  nhahtdh Nov 28 '14 at 7:36

protected by Josh Crozier May 21 '14 at 21:53

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.