Quiz

Explain the concept of hoisting with regards to functions

Topics
JavaScript

TL;DR

"Hoisting" describes the observable result of declarations being instantiated before a scope's statements execute; the engine does not move source text. A function declaration's binding is initialized with the function during scope setup, so it can be called earlier in that scope. A function or arrow expression is created only when evaluation reaches the expression. Its variable binding follows the rules for var, let, or const.

// Function declaration
hoistedFunction(); // Works fine
function hoistedFunction() {
console.log('This function is hoisted');
}
// Function expression
nonHoistedFunction(); // Throws an error
var nonHoistedFunction = function () {
console.log('This function is not hoisted');
};

What is hoisting?

Hoisting is informal terminology for the way JavaScript creates bindings while instantiating a scope before executing its statements. Function declarations are initialized during that process, which allows them to be called before their declaration appears in source order.

Function declarations

Function-declaration bindings are initialized with their functions during scope setup. This means you can call a function before its declaration appears in source order.

hoistedFunction(); // Works fine
function hoistedFunction() {
console.log('This function is hoisted');
}

Function expressions

Function expressions, including arrow functions, are evaluated in place. With var, the variable binding exists and initially contains undefined; with let or const, the binding is in the temporal dead zone until its declaration is evaluated.

nonHoistedFunction(); // Throws an error: TypeError: nonHoistedFunction is not a function
var nonHoistedFunction = function () {
console.log('This function is not hoisted');
};

Arrow functions

Arrow functions behave similarly to function expressions in terms of hoisting.

arrowFunction(); // Throws an error: TypeError: arrowFunction is not a function
var arrowFunction = () => {
console.log('This arrow function is not hoisted');
};

Further reading

Exercises

Check your understanding
Beta
Check your understanding Exercise
Check your understanding Exercise

What happens when this classic script runs?

console.log(typeof declared);
console.log(typeof expressed);
declared();
expressed();
function declared() {}
var expressed = function () {};