Hoisting is a Javascript mechanism where variables and functions are moved from where they appear.

  • Only declarations are hoisted. Assignments or other executable logic are left in place.
  • Functions are hoisted first and then variables.
var x =2;

Javascript thinks of it as two statements: var x and x = 2.
The first statement var x is executed during the compilation phase while the second statement x = 2 is left in place for the execution phase.

For example:

(function() {
    console.log(x); var x =2;  // undefined
})();

The execution of the above code is done in the following steps:

  1. var x;
  2. console.log(x); // at this step is undefined.
  3. x = 2;
(function() {
    x=2; 
    var x; 
    console.log(x); // 2
})();

The execution of the above code is done in the following steps:

  1. var x; // declaration is hoisted.
  2. x = 2;
  3. console.log(x); // 2 is printed.

function foo’s declaration is hoisted:

(function(){
    foo();
    function foo(){
        console.log(a);  //undefined
        var a = 2;
    }
})();

function expressions are not hoisted:

(function(){
    foo();
    var foo = function bar(){
    };
})(); // TypeError
(function(){
    foo();
    function foo(){
        console.log('a');
    }
    
    foo = function foo(){
        console.log('b');
    }
})(); // prints a

Subsequent Javascript functions overrides the previous ones.

(function() {
foo(); // prints c

function foo() {
    console.log('a');
}

var foo = function() {
    console.log('b');
};

function foo() {
    console.log('c');
}
})();

Reference: You Don’t Know JS