Unknown Story of Hoisting in JavaScript
Description:
Hey Developers, most of the time we declare variables at top of programs and use it in functions , modules whenever required . Although there may exist some scenarios where in we may want to declare variable at runtime but want to use it before its declaration. This is where hoisting come to picture.
First of all ,a simple and funny question might stuck in your brain , whether ‘hoisting’ and ‘hosting’ are same.
Although they might sound same but are entirely different.
Hosting:
Hosting is all about making website visible to people by deploying it on some server.
Hoisting:
Hoisting is about accessing certain variables even before declaring it.
Let’s see an example of Hoisting in JavaScript programming below:
x = 100 // assigning an undeclared variable a value console.log(x) //x = 100 var x; // declaration of variable x after definition is already been declared. y = 200 // assigning an undeclared variable a value let y; // "ReferenceError", variables cannot be accessed before their declaration z = 300 const z; // "ReferenceError", variables cannot be accessed before their declaration
Here,we can clearly see that variables declared using ‘var’ keyword can be accessed before when thy are accessed.
But its not true for ‘const’ and ‘let’ keywords as they will throw syntax error.
Hoisting is simple and sweet concept of defining variable even before declaration.
Hey Developers , I do hope that its very much clear now about hoisting concept in JavaSscript.
Thank you very much.
Great article.Thanks for increasing my JS knowledge.