- Global Execution Context has two phases :
(i) Creation Phase
(ii) Execution Phase
(i) Variable Hoisting
(ii) Function Hoisting
(i) Variable Hoisting :
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:
(ii) Function Hoisting :
Before Hoisting After Hoisting
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.
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.
- Declare all of your variables to the top of the scope.
- Make sure all your functions are put at the top of the scope.