Problem with Javascript global variable

I ran into a problem 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 throw an undefined problem in someF2() ? Why can someF2() access someGlobal and someF() not? How can I make sure a global variable is available in a function?

Note:

In both cases, the functions begin by calling alert(someglobal) , why does one function cause the undefined problem and the other not?

+6
source share
4 answers

someF creates a new (local area) variable called someGlobal (which masks the global someGlobal ) and assigns a value to it. It does not concern the global someGlobal (although it cannot access it because there is another variable with the same name in the area).

Operators

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

someF2 access the original (untouched) global someGlobal .

+7
source

Since you are declaring a local variable with the same name. Therefore, it assigns a value to a local variable. Just remove var from var someGlobal in someF () and everything 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(); 
+4
source

someF2 displays 3 because it is still 3.

In someF (), you create a new variable that has the same name as someGlobal. This does nothing for the original someGlobal, it just creates a new variable locally for the someF function, which disappears when this function ends.

So, you have local variables (e.g. created inside someF with var) and global.

+1
source

The following is an example of using local and global variables inside someF using this .

 var someGlobal = 3; function someF() { // Displays 3 alert(someGlobal); this.someGlobal = 5; someGlobal = 5; // Displays 5 alert(this.someGlobal); } function someF2() { // Displays 5 alert(someGlobal); } someF(); someF2(); 

-1
source

All Articles