Hoisting 🚩 in JavaScript!
Let’s understand what is hoisting in JavaScript and how does it work with the help of some examples 🌟
The above code is a normal JavaScript program, whose output is:
- Sridhar Maskeri
- 7
What happens if we call the function while also attempting to print the variable before declaring them? 🤔
Now the output is:
- Sridhar Maskeri
- undefined
The phenomenon that occurs in the above example is called as Hoisting 🚩 in JavaScript.
Hoisting🚩 in JavaScript allows us to access variables and functions even before declaring or initialising them.
The Creation phase and the Execution phase are the two distinct phases that make up each Execution Context, and each has its own distinct duties.✨
The JavaScript engine will begin the Global Creation phase by :
- Creating a global object.
- Creating an object called “this”.
- Setting up memory space for variables and functions.
- Assigning variable declarations a default value of “undefined” while placing any function declarations in memory.
In plain English, this means that the code is first scanned, the variables and functions are given a reserved area in the memory, and only then is the line-by-line execution of the code carried out.
Get Sridhar Maskeri’s stories in your inbox
Join Medium for free to get updates from this writer.
This is the reason why the value of x is undefined in Example 2.
Now let’s try to print the value of x after it has been initialised. 🤠
Yes you got it right 👏, now the output will be:
- undefined
- 7
Now let’s try to print the value of a variable that is never initialised or declared. 🤠
Output :
- Sridhar Maskeri
- Here we get an error : Uncaught ReferenceError: x is not defined
Here we do not get undefined since the variable x is never declared or initialised in the entire program. 😯
Let’s now examine what would happen if the function getName() was an arrow function. 🧐
Output :
We get an Error : Uncaught TypeError : getName is not a function
This is because the arrow function acts as a variable rather than a function. Hence it initially stores the value undefined. 😯
I hope you at least have a rudimentary understanding of hoisting now that you know what it is and how it works in JavaScript. 🤗
Video Reference : https://www.youtube.com/watch?v=Fnlnw8uY6jo&list=PLlasXeu85E9cQ32gLCvAvr9vNaUccPVNP&index=4
Happy Coding :) 🙌









