28
Oct
07

JS function object properties

What would you think is the output of the following java script?

var scope = global;
function scopetest(){
alert(scope);
var scope = local;
alert(scope);
}
scopetest();

Coming from languages like PHP or C++ one would expect the output to be:
global
local

But in Java script it is:
undefined
local

The reason behind is, that in this case, java script creates a function object at the time when the function is called. Then the interpreter looks up the properties of this new function object and declares each the declared function vars in as function object properties. When this process is finished, java script begins to execute the function.

Thus, when the function object is created, the global variable is hidden by the local one. The variable scope is defined at the time of the first alert, but no value is assigned to it.

To avoid headache when coding, its best practice to declare all variables used in a function at the top of the function.


0 Responses to “JS function object properties”


  1. No Comments