Hoisting is a cool feature in JavaScript that allows us to use a variablebefore even declaring it.
Which means we can start using a variable before we even declare it.
<html> <body> <script> document.write(x) var x </script> </body> </html>
So, we got the output as undefined. That's fine. Because the variable x is not initialised with any value.
However, we didn't end up with an error.
Now, what if, we try the next example, where we do not declare the variable x at all.
<html> <body> <script> document.write(x) </script> </body> </html>
Now, that we have not defined the variable x. We have ended up with an error,
Error: x is not defined
Now, let us come to the previous example,
document.write(x) var x
Even though we have declared the variable x after it is used. We still didn't end up with an error.
This is because JavaScript moves all the declaration to the top. This is called as Hoisting.
But just remember, if you initialise a variable, that will not be Hoisted.
<html> <body> <script> document.write(x) var x = 5 </script> </body> </html>
So, in the above example, even though, we have assigned the value of x with 5. Still we got the value as undefined.
That is because the initialisation of a variable is not Hoisted.