0

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

SHRX
  • 559
  • 1
  • 6
  • 17
  • Declarations don't do anything at runtime, so what does your question even mean? – melpomene Mar 15 '19 at 13:31
  • 1
    Possible duplicate of [How does hoisting work if JavaScript is an interpreted language?](https://stackoverflow.com/questions/45620041/how-does-hoisting-work-if-javascript-is-an-interpreted-language) – Nick Parsons Mar 15 '19 at 13:32
  • i want to know if the declaration of var b happens right after the declaration of var a after hoisting or if it will be declared when xyz() is executed – SHRX Mar 15 '19 at 13:33
  • JS execution is from my understanding quite bound to the JavaScript engine (as some engines compiles some of the code), so it depends on what engine you use. – Jite Mar 15 '19 at 13:33
  • Again, declaring a variable doesn't "do" anything. It "happens" at parse time, when the JS compiler reads your code. – melpomene Mar 15 '19 at 13:44
  • 1
    The duplicate contains the exact explanation how it works, including references to the spec. – Shilly Mar 15 '19 at 13:53

1 Answers1

2

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)
R3tep
  • 12,512
  • 10
  • 48
  • 75
  • Do you possibly have a source for this? All the articles about hoisting i read up until now did not specify this and i'd love to know more about it :) – SHRX Mar 15 '19 at 13:35
  • 1
    @SHRX I make you a live demo, like that you can see the variable declaration is not working if you don't call the function. So the variable is not declared during interpretation. – R3tep Mar 15 '19 at 13:46
  • Oh thats so nice, but i think it won't be necessary, your comment clearly tells me how i can test that myself. thanks so much :) – SHRX Mar 15 '19 at 13:49