javascript global variable with 'var' and without 'var'

Moon picture Moon · Aug 1, 2011 · Viewed 12.1k times · Source

Possible Duplicate:
Difference between using var and not using var in JavaScript

I understand that I should always use 'var' to define a local variable in a function.

When I define a global function, what's the difference between using 'var' ?

Some of code examples I see over the internet use

var globalVar = something;
globalVar = something;

What's the difference?

Answer

Christian C. Salvadó picture Christian C. Salvadó · Aug 1, 2011

Well, the difference is that technically, a simple assignment as globalVar = 'something'; doesn't declare a variable, that assignment will just create a property on the global object, and the fact that the global object is the last object in the scope chain, makes it resolvable.

Another difference is the way the binding is made, the variables are bound as "non-deletable" properties of its environment record, for example:

var global1 = 'foo';
delete this.global1; // false

global2 = 'bar';
delete this.global2; // true

I would strongly encourage you to always use the var statement, your code for example will break under ECMAScript 5 Strict Mode, assignments to undeclared identifiers are disallowed to avoid implicit globals.