Table of contents
No headings in the article.
In these post we will discuss about the main idea of hoisting in variable.
Hosting in variable -
- For var keyword -
If we are given with the following code snippets -
console.log(newVar); /* => undefined */ var newVar = "random string"
For the code declared above, the javascript engine will take the var and the variable name to the top before any expressions and will declare it and also will initialise it as undefined. The code given above can be expressed as below -
var newVar; console.log(newVar); /* => undefined */ newVar= "random string"
- For let and const keyword -
If the code is declared as follows -
console.log(newVar); let newVar = "random string"
console.log(newVar); const newVar = "random string"
For the code declared above, the javascript engine will take the let / const and the variable name to the top before any expressions and will declare but will not initialise it and so it will give reference error as logged. The code given above can be expressed as below -
const newVar; console.log(newVar); /* => reference error */ newVar= "random string"
It is much important to understand hoisting in such variables as later one may get confuse while using anonymous or arrow functions or simply using it as a hoisted variable in the the code.