Hoisting

suggest change

What is hoisting?

Hoisting is the name for creating var and function-declaration bindings before the step-by-step execution of their scope. Assignments still happen where they are written. let and const are created early too, but they stay in the temporal dead zone until their declaration runs, so an early read throws ReferenceError instead of returning undefined.

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;
}

A function declaration is different. The whole declaration is available throughout its scope, unlike a function expression. 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

JavaScript hoists the declaration, not the initializer.

These scripts therefore produce different results. alert is browser-only.

var x = 2; 
var y = 4; 
alert(x + y);

This will give you an output of 6. But this…

var x = 2; 
alert(x + y);
var y = 4;

This alerts NaN. y is hoisted and is undefined when alert runs, and 2 + undefined is NaN. The declaration did run; the initializer did not.

The second example is the same as:

var x = 2; 
var y;
alert(x + y);
y = 4;

This will give you an output of NaN.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents