Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Global & Local Scope in Javascript

Tags:

javascript

I've been learning Javascript using Object-Oriented JavaScript by Stoyan Stefanov

He offers an example comparing global and local scope:

var a = 123;
function f() {
    alert(a);
    var a = 1;
    alert(a);
}
f();

Looking at this example, I expected the first alert to be '123' and the second alert to be '1'. Lo and behold, Stoyan says:

You might expect that the first alert() will display 123 (the value of the global variable a) and the second will display 1 (the local a). This is not the case. The first alert will show “undefined”. This is because inside the function the local scope is more important than the global scope. So a local variable overwrites any global variable with the same name. At the time of the first alert() a was not yet defined (hence the value undefined) but it still existed in the local space.

The explanation was not clear to me, how can the local variable overwrite the global variable in the first alert? Any other/different explanations would be appreciated.

like image 311
steve-er-rino Avatar asked Aug 13 '12 17:08

steve-er-rino


2 Answers

It is not overriding the global variable. What is happening is called "variable hoisting". That is, a var a; gets inserted at the top of the function.

The script engine changes your script to be the following:

var a = 123;
function f() {
    var a;
    alert(a);
    a = 1;
    alert(a);
}
f();

Lesson to learn: Always declare your variables before you use them. Some will say declare all your variables at the top of the function.

like image 96
Juan Mendes Avatar answered Oct 06 '22 00:10

Juan Mendes


In simple words, all the declarations, of both variables and functions are considered first. So local var a in effect will override global variable only in local scope and will have no value i.e. undefined. So first alert will show undefined. Second alert will show 1 as it is after a = 1. This just happens locally and global variable a will have value 123 - it won't be changed.

another example using function to show how it works

 function show(){
    alert("I am global");
 }

 function f() {

    show();

    show = function(){
       alert("I am second");
    }  

    show();   

    function show(){
        alert("I am first");
    }

}
f();
show();
like image 31
Diode Avatar answered Oct 05 '22 22:10

Diode