Enjoy 20% off all plans by following us on social media. Check out other promotions!
测验题

Explain the concept of hoisting with regards to functions

Topics
JAVASCRIPT
在GitHub上编辑

TL;DR

Hoisting in JavaScript is a behavior where function declarations are moved to the top of their containing scope during the compile phase. This means you can call a function before it is defined in the code. However, this does not apply to function expressions or arrow functions, which are not hoisted in the same way.

// 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 a JavaScript mechanism where variables and function declarations are moved to the top of their containing scope during the compile phase. This allows functions to be called before they are defined in the code.

Function declarations

Function declarations are fully hoisted. This means you can call a function before its declaration in the code.

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

Function expressions

Function expressions, including arrow functions, are not hoisted in the same way. They are treated as variable assignments and are only hoisted as undefined.

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

在GitHub上编辑