Hoisting is a phenomenon in JavaScript where you can access variables and functions even before initializing them.
Let’s look at an example of a code block below 👇
Before I execute this code, what do you expect to see? 🤔
We’re attempting to access the getName() function and the age variable before they've been initialized.
In the case of variables, it shows undefined, but for functions, it displays the results, whether it’s a function statement or when invoked. It’s quite strange how it works since we don’t see what’s happening behind the code.
Whenever you execute code, an execution context is created in two phases: memory creation and code execution. As soon as the code starts executing, memory is allocated to each variable and function. Even before the code starts executing, memory is allocated.
If we dig into the global scope, we’ll see that the variable x has already been allocated memory even before the code is executed.
In the case of functions, we get the actual copy of the function stored in memory instead of an undefined placeholder.
Until now, we have seen function invocation and variable access after the function statement and variable declaration. Let’s see what happens when we move the function invocation and variable access to the top.
Again, we have put the debugger on the first line of the code. Even before this first line’s execution, the variables and functions are already in the memory space.
Now, if everything is executed line by line, you can observe the output shown in the console 👇
Moving forward, we have seen enough about undefined, but have you ever thought about the difference between undefined and not defined? By observing the code block below, if I comment out the variable declaration and then execute the code, what will happen?
We have not reserved memory for the variable x in the global memory space. So, when it tries to access x and it is not found in the global object, JavaScript will throw a reference error saying x is not defined.
Connect with me 🍕
If you have any questions, feel free to reach to me on LinkedIn 🚀