Search code examples
javascripthoisting

JavaScript 'hoisting'


I came across JavaScript 'hoisting' and I didn't figure out how this snippet of code really functions:

var a = 1;

function b() {
    a = 10;
    return;

    function a() {}
}

b();
alert(a);

I know that function declaration like ( function a() {} ) is going to be hoisted to the top of the function b scope but it should not override the value of a (because function declarations override variable declarations but not variable initialization) so I expected that the value of the alert would be 10 instead of 1!!


Solution

    1. The global a is set to 1
    2. b() is called
    3. function a() {} is hoisted and creates a local variable a that masks the global a
    4. The local a is set to 10 (overwriting the function a)
    5. The global a (still 1) is alerted