Search code examples
javascriptscopehoisting

JavaScript scope gets changed? Why does this happen?


The value of 'a' seems to lose global scope when the constructor a is called.

var a = 6;

function b() {
    a = 10;

    function a() {}
    console.log(a); //10
}
b();
console.log(a); //6

Solution

  • The order is interpreted as shown below due to variable hoisting. Note that as @ShadowCreeper correctly points out, function a(){} is actually creating a local variable a inside of function b which is hoisted as shown below.

    var a;
    var b;
    
    a = 6;
    b = function() {
     var a;
     a = function(){};
     a = 10;
     console.log(a); //10
    }
    b();
    console.log(a); //6