Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript global variable scope issue

I am running into a strange scope issue with Javascript (see JSFiddle):

var someGlobal = 3;

function someF() {
    // undefined issue
    alert(someGlobal);
    var someGlobal = 5;
    // Displays 5
    alert(someGlobal);
}

function someF2() {
    // Displays 3, why?
    alert(someGlobal);
}

someF();
someF2();

Why doesn't Javascript throws an undefined issue in someF2()? How come someF2() can access the someGlobal, and someF() not? How can I make sure a global variable is accessible in a function?

Remark:

In both cases, the functions start by calling alert(someglobal), why does one function throw an undefined issue and the other not?

like image 985
Jérôme Verstrynge Avatar asked Jan 02 '13 12:01

Jérôme Verstrynge


2 Answers

someF creates a new (locally scoped) variable called someGlobal (which masks the global someGlobal) and assigns a value to it. It doesn't touch the global someGlobal (although cannot access it because there is another variable with the same name in scope).

var statements are hoisted, so someGlobal is masked for all of someF (not just after the var statement). The value of the local someGlobal is undefined until a value is assigned to it.

someF2 access the original (untouched) global someGlobal.

like image 125
Quentin Avatar answered Sep 21 '22 12:09

Quentin


Since you are declaring a local variable with the same name. So it assigns the value to the local variable. Just remove the var from var someGlobal in someF() and it should be fine.

var someGlobal = 3;

function someF() {
    // undefined issue
    alert(someGlobal);
    someGlobal = 5; // <-- orignially var someGlobal = 5
    // Displays 5
    alert(someGlobal);
}

function someF2() {
    // Should display 5 now
    alert(someGlobal);
}

someF();
someF2();
like image 44
Ali Avatar answered Sep 18 '22 12:09

Ali