Search code examples
javascripthoisting

Are vars in a function scope hoisted to the beginning like vars in the global scope?


i wasn't able to find a clear answer, so i'll try it here.

EDIT: this question is not about wether a var will be available from the beginning of the scope it is in, rather i'd like to know if the var is declared when the global vars are declared, or when the function is called.

Consider this example:

var a = "foo";
function xyz(){
    var b = "bar";
}
xyz();

when i run this code, where will the var b be hoisted to?

will it be:

declare function xyz
declare var a
assign value "foo" to var a
execute xyz()
>> declare var b
assign value "bar" to var b

or will it be:

declare function xyz
declare var a
>> declare var b
assign value "foo" to var a
execute xyz()
assign value "bar" to var b

I know that var b is not accessible from the global scope, but i'm curious in which order things are happening here.

Thanks in advance


Solution

  • The variable b is initialised when you execute xyz(), It's not initialised during the interpretation.

    function host() {
      var b;
    }
    var a;
    
    var aIsDeclared = true; 
    var bIsDeclared = true; 
    
    try{ a; }
    catch(e) {
        if(e.name == "ReferenceError") {
            aIsDeclared = false;
        }
    }
    
    try{ b; }
    catch(e) {
        if(e.name == "ReferenceError") {
            bIsDeclared = false;
        }
    }
    
    console.log("a is declared : ", aIsDeclared)
    console.log("b is declared : ", bIsDeclared)