JavaScript | Hoisting

In JavaScript, Hoisting is the default behavior of moving all the declarations at the top of the scope.
As in JavaScript, a variable can be declared after it has been used.
Note: JavaScript only hoists declarations, not the initializations.

Let us understand what exactly this is:

Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
<body>
  
<p id="GFG"></p>
  
<script>
  
// 10 is assigned to 'value'
value = 10; 
  
// Finding the element 
elem = document.getElementById("GFG"); 
  
// Display 'value' in the element
elem.innerHTML =value;                 
  
// Declaration of 'value'
var value;                       
</script>
</body>
</html> 

chevron_right


Output : 10

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
<body>
  
<p id="GFG"></p>
  
<script>
  
// Declaring  value
var value; 
  
// 10 is assigned to value
value = 10; 
  
// Find an element
elem = document.getElementById("GFG"); 
   
// Display value in the element
elem.innerHTML = value;                
</script>
</body>
</html> 

chevron_right


Output : 10

In both the cases the interpretation is same.

In JavaScript , initializations are not Hoisted
Let us take the case of initializations.
Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
<body>
  
<p id="GFG"></p>
  
<script>
  
// Initialize a
var a = 10; 
  
// Initialize b
var b = 20; 
  
// Finding  an element
element = document.getElementById("GFG");  
  
// Display a and b
element.innerHTML = a + " " + b;           
  
</script>
</body>
</html> 

chevron_right


Output : 10 20

And now let us take the other case.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
<body>
  
<p id="GFG"></p>
  
<script>
  
// Initializing a
var a = 10;  
  
element = document.getElementById("GFG");            
element.innerHTML = "A is " + a + " and B is " + b;  
  
// Initialize b
var b = 20;  
</script>
</body>
</html> 

chevron_right


Output : A is 10 and B is undefined


My Personal Notes arrow_drop_up

Lets get started

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.