Hoisting in JavaScript

Hoisting in JavaScript

Heyy Beginners, Lets understand Hoisting in JavaScript in Simple way!

Hoisting is a very popular concept in JavaScript. Lets understand it in a simple way. So, Hoisting is a concept in JavaScript in which all the Variable declarations, function declarations, class declarations are moved on top of the scope. Thus, we can safely use a variable before its declaration. Also, we can call the functions safely before their declarations. so first we will see how the functions are hoisted :

Function Hoisting

printAge(18);  // output : 18
function printAge(age){
      console.log(age);
}

In the above code, due to hoisting, we can call the function printAge() before its declaration. This is an example of Function hoisting.

Now, lets see Variable hoisting. In JavaScript, all the variables are hoisted. In case of let and const variables we get reference error because of temporal dead zone ⤴️Temporal Dead Zone. In case of var variable we get undefined because a var variable is always initialized with undefined when it is declared. Note that, a Variable is hoisted only if it is declared or it is declared and initialized at the same time. The variables which are only initialized without declaring are not hoisted. let us understand this through example:

declaration and initialization

 var num; //declaration
 num = 12;  //initialization
 var num = 12 // Declaring and Initializing at the same time

Variable Hoisting

console.log(a);   // output : undefined
var a = 12; // initialization
console.log(a); // output : 12
console.log(b); // output : referenceError
let b = 13; 

// Same behaviour in case of const variable also

If we only initialize a variable without declaring, then that variable is not hoisted. for example below code :

console.log(a); // output : referenceError
a = 25;

Advantage: The main Advantage of Hoisting is We don't have to see where the variables and functions are declared and what is there scope. because due to hoisting, all the declarations are moved to the top of the scope.