11

Possible Duplicate:
JavaScript Variable Scope

My understanding it that with in a function if I use var then I have a local variable. If I do not delcare var I now have a global variable.

But what about oustide of functions, what effect does var have?

Community
  • 1
  • 1

6 Answers6

10

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

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

As for what effect var has, it "declares" a variable:

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

vs:

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

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

alert(window.foo);

without declaring the variable with var, you get a lookup error, the same as trying to access the property of any object that doesn't exist.

Note that one of the oddities of var is that all declarations are pulled to the top of the script, so this will work as well:

alert(foo); // undefined
var foo;

You will also have access to your variable in the window object (though you will also have this by setting the variable without var, e.g. just foo=42):

var foo;
for(var key in window){
   // one of these keys will be 'foo'
}
  • This "The reason for this is that the above code is functionally identical to: `alert(window.foo);`" is badly wrong. Try this: http://jsfiddle.net/zeKhL/ – c-smile Jun 09 '11 at 22:45
  • 1
    @c-smile : it's not wrong. jsfiddle wraps code in an anonymous function by default. http://jsfiddle.net/cwolves/zeKhL/1/ –  Jun 09 '11 at 22:47
  • @Chris - in many of cases it doesn't matter outside of functions. The simplest case where it does is simply having the code `if(some_var){` where you will get an error "some_var is not defined" if the variable was never set OR declared with `var` –  Jun 09 '11 at 23:08
  • Really? You won't use it to save 4 bytes? :P –  Jun 09 '11 at 23:15
  • You realize that's roughly .00003 seconds of download time over a 1mb connection. –  Jun 09 '11 at 23:26
  • 1
    @ChrisAaker _always_ use `var`. No exception. If you want a global set `window.foo = ...`. This is a _BIG_ advantage for maintenability and readability. Just do it, you'll thank yourself. – Raynos Jun 09 '11 at 23:35
  • @ChrisAaker you sound like one of those micro optimising devils. It's the HTTP protocol, cmon it's slow as hell anyway. Now if you were hand optimising UDP packets then fair game. Oh and I forgot to mention stop writing JavaScript make sure you use native client wherever possible. (Its faster!) – Raynos Jun 09 '11 at 23:59
6

It is good practice to always use var. Strictly speaking when you are already in the global scope you don't need to but for the sake of code maintainability you should.

Say you have:

foo = 'bar';

But later you decide you want to move this code into a function:

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

If you forget to add a var statement you've just created an implicit global. Now if you create a new object in the global scope that is named foo they will cause conflicts with one another.

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

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

This kind of error is particularly insidious when you forget to use var on something like i in a for loop. Learning to use JSLint can help to avoid these and other problematic logic or syntax errors.

Useless Code
  • 12,123
  • 5
  • 35
  • 40
  • 1
    +1 for discussing the code maintenance angle. Even if code without `var` is 100% bug free today, it will be easier to understand when you come back to it next month if you know you follow the routine of always using `var` - otherwise when you see `foo = 'bar'` you have to search elsewhere to find out if `foo` was already declared or set to some other value, etc. – nnnnnn Jun 09 '11 at 23:59
1

Your question is answered in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var

Using var outside a function is optional; assigning a value to an undeclared variable implicitly declares it as a global variable. However, it is recommended to always use var, and it is necessary within functions in the following situations:

  • If a variable in a scope containing the function (including the global scope) has the same name.
  • If recursive or multiple functions use variables with the same name and> intend those variables to be local.

Failure to declare the variable in these cases will very likely lead to unexpected results.

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
Shanti
  • 1,230
  • 1
  • 9
  • 7
0

I believe using var outside of a function works the same as not using var: you get a global. The exception to this would be if you are in a class or some other namespace structure, in which it will still define a variable in that locale

Ben Roux
  • 7,308
  • 1
  • 18
  • 21
0

i believe you want to create a var whenever you are initializing a variable. As i've coded, when ever i need to initialize a variable, i start it with var. If you declare a variable without the word var, it's always global. If you declare a variable with var, inside a function, it's local to that function. If you create a variable with var outside functions, it will be a global variable.

Kevin Mansel
  • 2,351
  • 1
  • 16
  • 15
0

If you are declaring a global variable and set a value it won't have any practical value, but as mentioned, it's best practice. If however you want to declare a variable without a value, you will need "var".

ldg
  • 9,112
  • 2
  • 29
  • 44