When do I use var?

Possible duplicate:
JavaScript scope

My understanding is that with the function, if I use var, I have a local variable. If I am not delcare var, now I have a global variable.

But what about function execution, what effect does var have?

+5
source share
6 answers

First of all, it is generally bad practice to use code outside functions. If nothing else, wrap your code with anonymous functions:

(function(){
    // code
})();

As for the var effect, it "declares" a variable:

var foo;
alert(foo); // undefined;

against

alert(foo); // error: foo is not defined

The reason for this is that the code above is functionally identical:

alert(window.foo);

var, , , .

, var , script, :

alert(foo); // undefined
var foo;

window ( , var, , foo=42):

var foo;
for(var key in window){
   // one of these keys will be 'foo'
}
+8

var. , , , .

, :

foo = 'bar';

, :

function doSomething() {
    foo = 'bar'; // oops forgot to add var 
}

var, . , foo, .

function doSomething() {
    foo = 'bar'; // Implicit global
}

foo = 'baz';
doSomething();
console.log(foo); // Returns 'bar', not 'baz'

, var - i for. JSLint .

+6

, var , var: . , - ,

0

, var . , , var. var, . var, , . var, .

0

, , , , . , "var".

0

All Articles