Hoisting is very important and tricky part in the javascript world .When a program loads into the js engine for execution it will not executed in the same way as we have writeen it.
*Hoisting * means during the declaration phase it will hoist (raise) all the variable declaration and function declaration to the top of the current scope .
Let, s understand it with the help of a example :
In the above example you have seen as we have writeen our program is not executed in the same way by the Javascript engine .So now its time to go more deep .Then you all will be able to understand why this happened.
When the js engine execute the code it will creates a global execution context and it has two phases .
First Phase(Declaration phase) :
In the first phase (declaration phase ) it will allocate memory to all the variables and function .
Highest priority is given to the function declaration. Javascript engine will move all the function declaration to the top .
Like this :
var keyword :
During the Execution phase variable declared with var keyword are initialized with undefined value whereas variable declared with let and const keyword are initialized during the execution time only but memory is being allocated to all the variables during the declaration phase only.
let and const keyword
But if your write the above same code and replace the var keyword with let and const then it will throw an error Because you can,t access a variable which is not initialized yet. Because variables declared with let and const are initialized during the execution phase only.
Function expressions
Function expressions are not treated as the same as function declaration .During the declaration phase they are treated as a variable .
Execution Phase
In the execution phase it will execute code line by line means synchronously . The reason why it will execute all the code line by line is that Javascript engine is single threaded .
I hope now all of you are able to understand what is hoisting in javascript .this article will must help you to understand this topic :)
Top comments (0)