Javascript Hoisiting

It is a mechanism in JavaScript that moves the declaration of variables and functions at the top. So, in JavaScript we can use variables and functions before declaring them. This is known as hoisting.

This hoisting is applicable only for declaration not initialization. It is required to initialize the variables and functions before using their values.

Variable hoisting

In this type of hoisting means the JavaScript engine moves the variable declarations to the top of the script. The following example declares the counter variable and sets its value to 1.

<script>
	console.log(counter); // undefined
	var counter = 5;
</script>

However, the first line of code will not cause an error because the JavaScript engine moves the variable declaration to the top of the script. Technically, the code looks like the following in the execution phase:-

<script>
	var counter;
	console.log(counter); // undefined
	counter = 5;
</script>

In technical terms, during the creation phase of the global execution context, the JavaScript engine places the variable counter in the memory and initializes its value to undefined.

Input:-
 <script>  
	    counter = 5;
     document.write("The value of counter is ", counter);        
     var counter;
</script>

Output:-

Function hoisting

Like variables in javascript, the engine also hoists the function declarations. It moves the function declarations to the top of the script. For example:

<script>  
	  let x = 10,
    y = 30;
	  let result = add(x,y);
    console.log(result);

    function add(a, b){
       return a + b;
    }
</script>

In the above example, we called the add() function before defining it. The above code is equivalent to the following:

<script>  
	  function add(a, b){
    	return a + b;
	  }
    let x = 20, y = 10;
	   let result = add(x,y);
     console.log(result);
</script>

In Javascript, during the creation phase of the execution context, engine places the add() function declaration in the heap memory. To be precise, the JavaScript engine creates an object of the Function type and a function reference called add that refers to the function object.

Input:-
 <script>  
	    let x = 10, y = 30;
	    let result = add(x,y);
     document.write(result);
     function add(a, b){
       return a + b;
     }
</script>

Output:-