javascriptecmascript-5hoistingfunction-expressionjavascript-function-declaration

Why do function declarations get hoisted and function expressions don't?


According to hoisting definition:

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution

Why do function declarations get hoisted and function expressions don't?


Solution

  • As per MDN,

    Conceptually, for example, a strict definition of hoisting suggests that variable and function declarations are physically moved to the top of your code, but this is not in fact what happens. Instead, the variable and function declarations are put into memory during the compile phase, but stay exactly where you typed them in your code.

    As you see, in a function expression, actual function is a value assigned to a named variable. So this named variable is hoisted. Even if you have a named function assigned, it still will not be hoisted as it is not a declaration and will be created later.

    Sample:

    function test() {
      console.log(fn, foo);
      
      var fn = function foo() {}
    }
    
    test();