Jul 21 2009
Global Variables in Javascript
Normally, global variables are considered evil but in Javascript they are still used considerably.
var test = "test"; console.log(window.test == "test");
Okay, this one is usual and expected.
if (true) {
var test = "new test";
}
console.log(window.test == "new test");
Declaring the same variable inside the expression also gives any variable global scope.
function smth() {
var test = "no new test";
}
smth();
console.log(window.test != "no new test");
When the same variable is declared using ‘var’ keyword inside a function expression, it won’t have global impact.
function smth2() {
test = "new new test";
}
smth2();
console.log(window.test == "new new test");
But when the same variable (test in our case) is used inside a function expression, it will continue it’s global effect.
function smth3() {
test2 = "new variable";
}
smth3();
console.log(window.test2 == "new variable");
This case is a bit interesting and odd. Even though, test2 has not been declared earlier, it will be treated as global variable now.
Hope this help!

Comments Off


