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?