Hoisting in JavaScript
Unseen forces lift declarations, enabling early access to variables and functions.
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.๐