Javascript Global Variables Weirdness
This is a simple test of the use of Global variables in Javascript. Now suppose the following code writing outside of any function, class or whatever.
k = "k";
var t = "t";
alert("gl: " + k);
alert("gl: " + t);
Will alert us of both variables with those nice little javascript alerts
Now suppose we add this function to the code above
function test() {
alert("t: " + k);
alert("t: " + t);
j = "J";
var l = "l";
alert("t: " + j);
alert("t: " + l);
k = "2k";
t = "2t";
}
Now we run the test.
test();
which Alerts all the variables.
But now if we try the following:
alert("gl after test: " + k +" - " + "gl after test: " + t);
Alerts us with the following line gl after test: 2k - gl after test: 2t. So Globals can be modified from within functions. But what happens to the variables that were defined within the function?
alert("gl: " + j);
//alert(”gl: ” + l); //This won’t run, l was scoped within test and can’t be accessed outside of test.
Conclusions: Variables initialized outside a function are global whether you use var or not. Variables initialized inside a function are not global if they are initialized with var, else they are global.



Leave a Reply
Comment Guidelines
Your Email is required but will not be published.
You can use the following HTML Tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>If you have never commented before your comment will have to be approved before it is shown. Sorry but there is too much comment spam.