Hoisting is a phenomenon by which we can access the variables and functions even before we initialize it.
Note: In above code we can access the getName() and x even though it is in the top. This type of code will show error in other languages but because of Hoisting we are able to access it.
How can we access it?
It is because of execution context as we learned before. Creation of execution context start with the 1st phase as memory creation phase. So, in this phase variables are initialized as undefined and functions are copied as it is. That is why we are able to access it.
When we run the above Javascript code we get function as output, As the functions are copied as it is in the memory creation phase of execution context.
How we can see the memory creation phase of execution with the help of browser developer tool?
Once we run the above Javascript code in our browser, We have to open the developer tools in our browser and first we should add a breakpoint in line number:16 of the code. Once we start debugging, the execution first pause in line number:16.Now click on the Global Tab and search for getName and x, we can see how memory is allocated for functions and variables in memory creation phase before we execute the whole program.
Below is the way how the function is stored
Below is the way how the variable is stored
Note :There are some special cases, if the function is defined as an arrow function or as an anonymous function then in memory creation phase it is stored as regular variable and the value will be undefined.
We can view the memory creation phase of the execution context in same way as we did for the earlier example.
There are also some scenarios where let and const shows different behaviour as compared to var such as reference error because of Temporal dead zone. In addition to that class also shows different behaviour such as reference error. You can refer to Hoisting mdn to know more.
PS:I will also post about Temporal Dead Zone.
Reference:@akshaymarch7 , @lukeshiru
Top comments (1)
Thank you LUKESHIRU for pointing this out. I have added this point in my post.