What is hoisting?

Hoisting is a mechanism which moves all variable and function declarations to the top of their scope. However, variable assignments still happen where they originally were.

For example, consider the following code:

console.log(foo);  // → undefined
var foo = 42;
console.log(foo);  // → 42

The above code is the same as:

var foo;             // → Hoisted variable declaration
console.log(foo);    // → undefined
foo = 42;            // → variable assignment remains in the same place
console.log(foo);    // → 42

Note that due to hoisting the above undefined is not the same as the not defined resulting from running:

console.log(foo);    // → foo is not defined

A similar principle applies to functions. When functions are assigned to a variable (i.e. a function expression), the variable declaration is hoisted while the assignment remains in the same place. The following two code snippets are equivalent.

console.log(foo(2, 3));     // → foo is not a function

var foo = function(a, b) {
    return a * b;
}
var foo;
console.log(foo(2, 3));     // → foo is not a function
foo = function(a, b) {
    return a * b;
}

When declaring function statements, a different scenario occurs. Unlike function statements, function declarations are hoisted to the top of their scope. Consider the following code:

console.log(foo(2, 3));  // → 6
function foo(a, b) {
    return a * b;
}

The above code is the same as the next code snippet due to hoisting:

function foo(a, b) {
    return a * b;
}

console.log(foo(2, 3));  // → 6

Here are some examples of what is and what isn’t hoisting:

// Valid code:
foo();

function foo() {}

// Invalid code:
bar();                     // → TypeError: bar is not a function
var bar = function () {};

// Valid code:
foo();
function foo() {
    bar();
}
function bar() {}

// Invalid code:
foo();
function foo() {
    bar();                // → TypeError: bar is not a function
}
var bar = function () {};

// (E) valid:
function foo() {
    bar();
}
var bar = function(){};
foo();

Limitations of Hoisting

Initializing a variable can not be Hoisted or In simple JavaScript Hoists declarations not initialization.

For example: The below scripts will give different outputs.