ChatGPT解决这个技术问题 Extra ChatGPT

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

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?

When chaining var declarations, does putting a newline after a comma affects the behavior? var x=1, y=2, [return]z=3;
Failing to use "var" also leaves you exposed in case the variable name you chose happens to be a previously defined global variable. See my journey of grief here: stackoverflow.com/questions/16704014/…
@Ray Toal's meloncard blog post (definitely worth a read) has moved to blog.safeshepherd.com/23/how-one-missing-var-ruined-our-launch
I'd never imagined a poem could inspire me consideration for a programmatic problem
@Gibolt but look at the question date, it's a kinda unfair summon a 2009 question to tell that. Even though, it's still valid as in current date for maintainability, there are out there a bunch of not "modern JS" code.

A
AmericanUmlaut

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

Is "not really much difference" == "No Difference"?
Well, actually yes, there's difference :) Whether that difference is important is another question. See my answer further down: stackoverflow.com/questions/1470488/…
I think that may be Alex's point, which is why he's written it using the "is equal to" operator!
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...
If you're in the global scope then there's no difference. >> there is a difference which is explained in the answer below
M
Massimiliano Kraus

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.


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.
@Mageek He might be taking about eval-declared variables which are deletable. I wrote a blog post about this once.
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
@kangax what if the last two lines of Alex's examples were mixed: var someObject = {} and someObject.someProperty = 5 ? Would someProperty become global, while the object it is a property of remains local?
The spec name for what @kangax calls the DontDelete flag is configurable (= false), you can read about this in regards to Object.defineProperty and Object.getOwnPropertyDescriptor
J
Jonathan Lonowski

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;
    }
}

Isn't the nearest scope outer where you define var global = false;?
@Snekse: 'nearest' doesn't apply when var global = false; is declared. In that declaration, 'global' is placed in the scope of outer() because 'var' is used in the declaration. Because 'var' is not used in inner(), it will change the value in the next level up, which is outer().
I wonder if you comment would change if you changed that line to var global = local; in which case the nears scope of local would be the "local" outer scope that is actively being defined. Though it gets strange if you would change that same line to var global = global in which case the nearest scope when searching for the value of global would be up a level at the global window scope.
t
thealtus

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


I didn't downvote you, but scope is probably a better word than window. You're whole explanation is a bit obtuse.
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."
+1 this is a really nice explanation--i have not heard the var/no var issue framed (no pun intended) like this before.
Most of this answer is deprecated with let in ES6.
@EvanCarroll This answer is also technically incorrect since omitting var doesn't declare any variable, instead it creates a deletable property on the global object, besides with ES5 "use strict" mode most of the answer is obviously not correct, also let wasn't even considered in this answer since at the time of the question there wasn't any reference to the javascript version (added yesterday) which imply that the standard of reference (at that time) was ECMA 262 3rd Edition.
C
Camille Goudeseune

Always use the var keyword to declare variables. Why? Good coding practice should be enough of a reason in itself, but omitting it 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.


"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 I think good coding practice is always sufficient reason if it's a recommended best practice, which this is and by several Javascript authors.
@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.
m
mehulmpt

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();
        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) eventually resulting in infinite loop


Yikes! I can just imagine all the bugs that could be caused by that typo.
i'm curious, why you are passing i as an argument to two()? (inside the for loop) is that redundant?
The argument is ignored in two() function encapsulated in one() function, since the function two() was defined without an parameter. You are quite correct, It is not needed since it plays not role.
Bug or feature?
W
Waqar

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.


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.
@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
@RyuKaplan Parsing/compiling is different from actually running the code.
G
Gibolt

Don't use var!

var was the pre-ES6 way to declare a variable. We are now in the future, and you should be coding as such.

Use const and let

const should be used for ~95% of cases. It makes it so the variable reference can't change, thus array, object, and DOM node properties can change and should likely be const.

let should be be used for any variable expecting to be reassigned. This includes within a for loop. If you ever write varName = beyond the initialization, use let.

Both have block level scoping, as expected in most other languages.


Replace all you 'var' by 'const' (replace all). You will quickly notice where are your re-assigned variables. If you have too many of them, you probably code anti-patternly: most reassignable variables can be embedded in closures or as object-properties. If you have a few: use 'let' for them. Finally, if some variables where not delared at all with 'var', they will stay undeclared, and are still present in the global space, beware. About @Gibolt comment 'within a for loop', it is also recommended to avoid such loops in "95% of cases" ;-): array methods are great.
By saying that const should be used in 95% of cases, it seems like we are going away from good practice and into dogma.
Having a big, bold, "Don't use var" on a question where the alternative is to use no keyword whatsoever is a dangerous way to structure and format your answer. Don't underestimate a person's disinterest in reading your second paragraph. Some people may be in a lazy mood or in a hurry and may get the wrong idea from this answer just because of the way it is structured and formatted. You don't explicitly mention that you're not advocating putting variables in the global scope.
P
Pranay Warke

another difference e.g

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

while

a = a || [] ; // a is undefined error.

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 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.
@EvanCarroll : it gets hoisted to top of scope and gets set to undefined instead of null.
k
kevinji

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.


W
Waqar

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

3
3 revs, 3 users 58%

This is example code I have written for you to understand this concept:

var foo = 5; 
bar = 2;     
fooba = 3;

// Execute an anonymous function
(function() {    
    bar = 100;             //overwrites global scope bar
    var foo = 4;           //a new foo variable is created in this' function's scope
    var fooba = 900;       //same as above
    document.write(foo);   //prints 4
    document.write(bar);   //prints 100
    document.write(fooba); //prints 900
})();

document.write('<br/>');
document.write('<br/>');
document.write(foo);       //prints 5
document.write(bar);       //prints 100
document.write(fooba);     //prints 3

The function is by no means "anonymous". In fact, it is about as visibly named as it can possibly be.
Thank you for editing your answer, in response to Ingo Bürk's comment, to make the "anonymous function" actually anonymous.
t
thisismydesign

@Chris S gave a nice example showcasing the practical difference (and danger) between var and no var. Here's another one, I find this one particularly dangerous because the difference is only visible in an asynchronous environment so it can easily slip by during testing.

As you'd expect the following snippet outputs ["text"]:

function var_fun() { let array = [] array.push('text') return array } console.log(var_fun())

So does the following snippet (note the missing let before array):

function var_fun() { array = [] array.push('text') return array } console.log(var_fun())

Executing the data manipulation asynchronously still produces the same result with a single executor:

function var_fun() { array = []; return new Promise(resolve => resolve()).then(() => { array.push('text') return array }) } var_fun().then(result => {console.log(result)})

But behaves differently with multiple ones:

function var_fun() { array = []; return new Promise(resolve => resolve()).then(() => { array.push('text') return array }) } [1,2,3].forEach(i => { var_fun().then(result => {console.log(result)}) })

Using let however:

function var_fun() { let array = []; return new Promise(resolve => resolve()).then(() => { array.push('text') return array }) } [1,2,3].forEach(i => { var_fun().then(result => {console.log(result)}) })


Thanks for the example @thisismydesign! In regard to the last two examples, why does the penultimate example log an array of 3 elements with text written thrice whereas the ultimate example only logs "text" once per element within the array? (I understand that the last one declares "array" as a variable and is therefore in the local scope, whereas the penultimate example omits this, making "array" a part of the implied global scope.) But, why how does this affect the output? Is it because the forEach "i" iterates over the function and all global variables?
D
Danrex

As someeone trying to learn this this is how I see it. The above examples were maybe a bit overly complicated for a beginner.

If you run this code:

var local = true;
var global = true;


function test(){
  var local = false;
  var global = false;
  console.log(local)
  console.log(global)
}

test();

console.log(local);
console.log(global);

The output will read as: false, false, true, true

Because it sees the variables in the function as seperate from those outside of it, hence the term local variable and this was because we used var in the assignment. If you take away the var in the function so it now reads like this:

var local = true;
var global = true;


function test(){
  local = false;
  global = false;
  console.log(local)
  console.log(global)
}

test();

console.log(local);
console.log(global);

The output is false, false, false, false

This is because rather than creating a new variable in the local scope or function it simply uses the global variables and reassigns them to false.


T
Tarik

I see people are confused when declaring variables with or without var and inside or outside the function. Here is a deep example that will walk you through these steps:

See the script below in action here at jsfiddle

a = 1;// Defined outside the function without var
var b = 1;// Defined outside the function with var
alert("Starting outside of all functions... \n \n a, b defined but c, d not defined yet: \n a:" + a + "\n b:" + b + "\n \n (If I try to show the value of the undefined c or d, console.log would throw 'Uncaught ReferenceError: c is not defined' error and script would stop running!)");

function testVar1(){
    c = 1;// Defined inside the function without var
    var d = 1;// Defined inside the function with var
    alert("Now inside the 1. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);

    a = a + 5;
    b = b + 5;
    c = c + 5;
    d = d + 5;

    alert("After added values inside the 1. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);
};


testVar1();
alert("Run the 1. function again...");
testVar1();

function testVar2(){
    var d = 1;// Defined inside the function with var
    alert("Now inside the 2. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);

    a = a + 5;
    b = b + 5;
    c = c + 5;
    d = d + 5;

    alert("After added values inside the 2. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);
};

testVar2();

alert("Now outside of all functions... \n \n Final Values: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n You will not be able to see d here because then the value is requested, console.log would throw error 'Uncaught ReferenceError: d is not defined' and script would stop. \n ");
alert("**************\n Conclusion \n ************** \n \n 1. No matter declared with or without var (like a, b) if they get their value outside the function, they will preserve their value and also any other values that are added inside various functions through the script are preserved.\n 2. If the variable is declared without var inside a function (like c), it will act like the previous rule, it will preserve its value across all functions from now on. Either it got its first value in function testVar1() it still preserves the value and get additional value in function testVar2() \n 3. If the variable is declared with var inside a function only (like d in testVar1 or testVar2) it will will be undefined whenever the function ends. So it will be temporary variable in a function.");
alert("Now check console.log for the error when value d is requested next:");
alert(d);

Conclusion No matter declared with or without var (like a, b) if they get their value outside the function, they will preserve their value and also any other values that are added inside various functions through the script are preserved. If the variable is declared without var inside a function (like c), it will act like the previous rule, it will preserve its value across all functions from now on. Either it got its first value in function testVar1() it still preserves the value and get additional value in function testVar2() If the variable is declared with var inside a function only (like d in testVar1 or testVar2) it will will be undefined whenever the function ends. So it will be temporary variable in a function.


Thanks for taking the time to create an example to demonstrate this topic. The code above is missing the part below so you might want to edit your answer: a = 1;// Defined outside the function without var var b = 1;// Defined outside the function with var alert("Starting outside of all functions... \n \n a, b defined but c, d not defined yet: \n a:" + a + "\n b:" + b + "\n \n (If I try to show the value of the undefined c or d, console.log would throw 'Uncaught ReferenceError: c is not defined' error and script would stop running!)");
A
Akash Arora

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

d
deathangel908

Besides scopes issue, some folks also mention hoisting, but no one gave an example. Here's one for global scope:

console.log(noErrorCase); var noErrorCase = "you will reach that point";

console.log(runTimeError); runTimeError = "you won't reach that point";


u
umut

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


my_var; is actually a valid expression statement.
It is valid statement if variable is defined before. Otherwise it throw an error "... is not defined".
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.
I am confused about it. What is valid statement? And can you give me an invalid statement example?
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.
s
systemdebt

You should use var keyword unless you intend to have the variable attached to window object in browser. Here's a link that explains scoping and difference between glocal scoping and local scoping with and wihtout var keyword.

When variables get defined without the use of var keyword, what it looks like is a simple “assignment” operation.

When the value is assigned to a variable in javascript, the interpreter first tries to find the “variable declaration” in the same context/scope as that of assignment. When the interpreter executes dummyVariable = 20, it looks up for the declaration of dummyVariable at beginning of the function. (Since all Variable declarations are moved to the beginning of the context by javascript interpreter and this is called hoisting)

You may also want to look at hoisting in javascript