Explain the concept of hoisting with regards to functions
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 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 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 finefunction 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 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');};