A Person with another programming background is definitely confused with hoisting in Javascript. So let’s deep dive into the hoisting in javascript
- The Javascript engine creates the global execution context when we execute a piece of Javascript code.
- Global Execution Context has two phases :
(i) Creation Phase
(ii) Execution Phase
Definition:
During the creation phase, the Javascript engine moves the variable and function declaration to the top of the code. This is called Hoisting in Javascript.
There are two types of Hoisting in Javascript
(i) Variable Hoisting
(ii) Function Hoisting
(i) Variable Hoisting :
In Variable Hoisting, the Javascript Code moves the variable declaration to the top of the code
Ex:
Here in this example, you may be confused why the output is undefined instead of error because we access variable a. So here the hoisting comes into the picture. And now you will know what the meaning of the variable goes to the top of the scope.
After Hoisting the Code:
So here the (var a) is hoisted to the top of the scope that is how the code runs behind the javascript. The variable (a) hoisted to the top of the scope and the javascript initialized this variable with undefined
(ii) Function Hoisting :
Like Variable function is also hoisted in javascript. Let’s see how
Ex:
Before Hoisting After Hoisting
Here in the first image is how you write a code and in the second image how the code actually runs behind the javascript. Behind the javascript, the function add is hoisted to the top of the scope.
Function Statements are Hoisted, but Function Expressions are not :
Now you will be confused what is the difference b/w function statement and function expression. So the above example is the function statement when we write a simple function and when we assign a process into a variable that is a function expression.
Ex:
Here in this example, this program will show an error: add is not a function because here add acts as a variable and it will be hoisted to the top of the scope when the program comes to line no. 4 the program will throw an error.
Conclusion:
- Hoisting is the Javascript default behavior of moving declaration to the top.
- Declare all of your variables to the top of the scope.
- Make sure all your functions are put at the top of the scope.
I hope you enjoyed this article Hoisting in Javascript 🙂