Table of Contents
Hoisting generally allows you to use a function and variable before they are being declared. In simple words we can define hoisting as a process in which the interpreter moves the declaration of the function, variables or classes to the top of their scope , prior to the execution of the code. In this blog post we will be taking a close look on what is hoisting and how it works.
Let us understand it with the help of an example
In other programming languages if you are trying access the value of variable without defining it then it will show an error . But the output of the above program will be undefined .
Variable Hoisting
When talking about variables and constants the keyword var is hoisted and let and const are also hoisted but not initialised with a default value .
Let us understand variable hoisting with the help of an example:
Example :
Output:
In the above example it is clearly visible that we are using variable x without defining it. And the program works fine and displays the output 6. The program behaves very similar to the below mentioned example.
Let and const hoisting in javascript
As we all know that the variables declared with let and const are also hoisted but unlike the var is not initialised with a default value. So for this reason an exception will be thrown if a variable declared with let or const is read before it is initialised.
Let us understand it with an example
Output
Always. make a note before writing javascript that the order in which the code is executed is what matters and not the order in which it is written down in the source file.
Function Hoisting
The best part about javascript is that the function can be called before executing it.
Let us see it with the help of an example:
Example:
Output:
In the above example it is clearly visible that the function getName is called before declaring it and the output is printed on the console. The reason for this is hoisting .
However when we use a function as an expression then an error occurs. This is because the declaration are only hoisted. Let us see it with the help of an example.
Example:
Output:
If let is used in the above program instead of var then the output will be:
Uncaught ReferenceError: Cannot access 'getName' before initialisation
Conclusion
- Hoisting generally allows you to use a function and variable before they are being declared.
- When talking about variables and constants the keyword var is hoisted and let and const are also hoisted but not initialised with a default value .
- As we all know that the variables declared with let and const are also hoisted but unlike the var is not initialised with a default value. So for this reason an exception will be thrown if a variable declared with let or const is read before it is initialised.