2

I am trying to understand variable hoisting in Javascript, specifically the order in which function declarations and variable declarations are hoisted. As I understand it, function declarations are hoisted first, followed by variable declarations.

The following two code snippets however let me think that variable declarations must come before function declarations in some cases:

bar();
function bar() {
  console.log(foo);
}
var foo; 

// The console will log: undefined

bar();
function bar() {
    console.log(undeclaredVariable);
}
/* As expected, the above throws:
 * "ReferenceError:  undeclaredVariable is not defined"
*/
  

In both cases the function bar gets hoisted, so I can immediately call it in the first line. But if variables like foo are hoisted after functions, shouldn't console.log(foo) also throw a ReferenceError in the first snippet, as console.log(undeclaredVariable) does in the second snippet, since it would not have been declared yet? What is the actual order, when it comes to the way Javascript processes variable declarations and hoisting?

GeYibo
  • 23
  • 4
  • 1
    tl;dr the "order" of hoisting doesn't matter because by definition nothing executes before any hoisted declarations, so everything will be declared. – Patrick Roberts Dec 20 '18 at 20:29
  • Possible duplicate of [Order of hoisting in JavaScript](https://stackoverflow.com/questions/28246589/order-of-hoisting-in-javascript) – Murad Sofiyev Aug 17 '19 at 20:42

2 Answers2

0

Both functions and variable declarations (but not assignment) are hoisted.

So in this example:

bar();
function bar() {
  console.log(foo);
}
var foo; 

Both the function declaration and the variable declaration are hoisted, then code like bar(); is executed.

The hoisting happens when the code is JIT compiled, with the code actually being executed after it is compiled.

Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
0

No it shouldn't throw an error because the function is not evaluated until bar() is called. The order doesn't matter: neither of these throws an error:

var foo; 
function bar() {
  console.log(foo);
}
bar();

function bar() {
  console.log(foo);
}
var foo; 
bar();

Because regardless of the hoisting order the names are declared before bar() is called and the function is executed.

Mark
  • 90,562
  • 7
  • 108
  • 148
  • 1
    Thanks, now I understand. I wrongly assumed the Javascript engine would alert me of such errors before running. But obviously Javascript is interpreted and not compiled, so this makes more sense – GeYibo Dec 20 '18 at 20:41