Explain the concept of hoisting with regards to functions
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 declarationhoistedFunction(); // Works finefunction hoistedFunction() {console.log('This function is hoisted');}// Function expressionnonHoistedFunction(); // Throws an errorvar 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 finefunction 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 functionvar 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 functionvar arrowFunction = () => {console.log('This arrow function is not hoisted');};