Search code examples
javascripthoisting

Are function declarations really hoisted before variable declarations?


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?


Solution

  • 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.