Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   
   HTML   
   CSS   
   JAVA SCRIPT   
   JQUERY   




JAVASCRIPT - HOISTING


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.


Hoisting for variables


Example :



<html>
<body>  
<script>
	
	document.write(x)
	var x
	    
</script>      
</body>
</html>


Output :



  undefined

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.


Example :



<html>
<body>  
<script>
	
	document.write(x)
	    
</script>      
</body>
</html>


Output :



  Error: x is not defined

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.


Example :



<html>
<body>  
<script>
	
	document.write(x)
	var x = 5
	    
</script>      
</body>
</html>


Output :



  undefined

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.