Hoisting in JavaScript
Guess what is the output of the program?
1 getName();
2 console.log(x);
3 var x = 7;
4 function getName() {
5 console.log('Namaste JavaScript');
6 }
Output is:
Namaste JavaScript
undefined
Why do we get the above output?
Due to Hoisting.
Now, What is Hoisting?
It is the phenomenon to use the variables and functions before their initialization or having value inside them.
Hoisting behind the scenes:
As we learned in the previous blog, during the memory allocation phase of the global execution context, memory is allocated to variables and functions. Variables declared with the var
keyword are assigned the initial value of undefined
, while function declarations are stored as their complete definitions.
This memory allocation process occurs before the code execution phase. As the JavaScript engine executes the code line by line during the code execution phase:
The
getName()
the function is invoked, leading to its execution and the logging of 'Namaste JavaScript' to the console. This is possible becausegetName
has a complete definition stored in memory during the memory allocation phase.The
console.log(x);
the statement is encountered. At this point, the variablex
has been declared but not yet assigned a value. Therefore, it executes and logsundefined
to the console, reflecting the initial value assigned during the memory allocation phase.
Conclusion:
You learned Hoisting in javascript in this blog. You can now research more about it online. If you'd like, you can connect with me on Twitter.
Gratitude for reading.
Resource:
Hoisting in JavaScript ๐ฅ(variables & functions) | Namaste JavaScript Ep. 3
Request:
If I make mistakes in the blog, please comment.๐
Subscribe to my newsletter
Read articles from Lovish Duggal directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Lovish Duggal
Lovish Duggal
I am a Full Stack Developer skilled in JavaScript Stack. I love building robust and scalable web solutions that make a difference. I enjoy creating user-friendly applications and contributing to open-source projects. My goal is to deliver high-quality code and collaborate with others to achieve great results.