Hoisting in JavaScript
Unseen forces lift declarations, enabling early access to variables and functions.

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.
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 becausegetNamehas a complete definition stored in memory during the memory allocation phase.The
console.log(x);the statement is encountered. At this point, the variablexhas been declared but not yet assigned a value. Therefore, it executes and logsundefinedto 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.🙏




