Techie's Venture

Hoisting in JS & its importance

What is Hoisting in Javascript?

Hoisting in Javascript is basically the ability to use or refer to a variable or a function before it has been declared in the code. The javascript interpreter does this by reading the whole code all at once then moving the variables at the top of the scope of the current execution context.

The first time the interpreter reads the code, it makes a Global Execution Context beforehand, where all the variables are hoisted or moved to the top of the scope. The interpreter just reads or skims through the code to find variables and functions which are then declared in the Variable Environment.

Variables are declared with undefined whereas in the case of functions, the whole block of code inside the function is stored in the memory. Although variables are declared before the code executes, you can only access the variables you have declared with the var keyword. The variables declared with let and const are temporarily moved to Temporal Dead Zone or TDZ in short, until their values are initialized.

We can see this behavior in action with the following example.

				
					console.log(a);     // undefined

var a = 'Hello';    // Initialized later
				
			

This code when executed will print undefined and not an error, even though the variable is initialized later in the code. This is because the variable is hoisted to the top of the scope before the execution of the code.

Let us look at another example showcasing the TDZ in action.

				
					console.log(a);     // undefined
console.log(b);     // Reference Error

var a = 'Hello';    // Intialized with var
let b = 'World';    // Initialized with let

				
			

In this case the code will output undefined for the first line and reference error for the second line. The reference error is due the Temporal Dead Zone mentioned before.

The same thing can be seen with the const keyword below:

				
					console.log(a);     // Reference Error

const a = "Hello";  // Initialized with const
				
			

Hoisting for functions can be seen in action with the following example:

				
					a();    // prints "Hello"    

function a(){   // Function is initialized later
    console.log('Hello');
}
    
				
			

This piece of code will output Hello when executed. Here, the function a() is called even before its declaration in line 3. This happens because the function is hoisted before the interpreter starts executing the code line by line.

Samipan Banerjee
All Posts

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts