Friday, November 19, 2010

to var or not to var

It's a quite interesting and yet confusing question:

What is the difference between declaration of a variable with and without "var"?


After reading the question and answers on Stack Overflow, I finally start to get it.


First, it affects the scope of the variable.

The variable defined without var means the nearest scope in the case of a hierarchical structure, e.g. embedding one function inside another function. In most cases, a declaration without var in a function means global scope (in many cases this means window object). The variable defined with var is bound to the scope of that function.

Second, it affects the delete behavior.

The variable defined with var cannot be deleted. The variable defined without var (actually, this is a property, not a variable in the true sense) can be deleted. The reason behind this that variable defined with var has a flag of DontDelete. See this nicely explained Stack Overflow post for details.

Lastly, the general guide is to always use var.

var i = 'hello';
j = 'world';
print("i=" + i + ", j=" + j); // i=hello, j=world
(testFunc = function() {
 var i = 'foo';
 print("inside function: i=" + i); // inside function: i=foo
 print("inside function: j=" + j); // inside function: j=world
})();
delete i;
print("i=" + i); // i=hello, ha, i still exists!
delete j;
print("j=" + j); // ReferenceError: j is not defined, j got deleted

Ok, one last exercise before I close this post. Guess what is the output for this code snippet:

func2_var = 'var outside';
func2_var2 = 'var2 outside';
func2 = function() {
 var func2_var = 'var in func2 body';
 this.func2_var2 = 'var2 in func2 this';
}
func2.prototype.func2_var = 'var in func2 prototype';

f2 = new func2();
print("which var it is: " + f2.func2_var);
print("which var2 it is: " + f2.func2_var2);

The END.

1 comment:

  1. answer:

    which var it is: var in func2 prototype
    which var2 it is: var2 in func2 this

    ReplyDelete