If you’ve ever wondered why you were able to call functions or use a variable before you wrote them in your code, hoisting is the reason why. Hoisting means that no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local. For example
In the above example, variable c is used before declaring it. And the program works and displays the output Comfort. The program behaves as:
Here, the variable c is declared before using it and the program display the output Comfort.
Variable and function declarations are hoisted to the top of their scope and not initializations.
So, if everything makes sense to you at this point and you understood it. Good job! You now know what hoisting is. But let’s push it a little further.
Hoisting is done within the context of declarations. In terms of variables and constants, the keyword
var is hoisted because the scope of a variable declared with the keyword
var is its current execution context. Whereas
const does not allow hoisting. Using a
let variable before it is declared will result in a
ReferenceError. This is known as the Temporal dead zone. And using a
const keywords, variables can now be declared using these keywords which are block-scoped by default, and are not hoisted.
- Function declarations
- Function expressions
Function declaration are hoisted completely to the top. However, when a function is used as an expression, an error occurs because only declarations are hoisted. Therefore function expressions are not hoisted. To avoid this pitfall, we would make sure to declare and initialise the variable before we use it.