Learn Hoisting in Javascript

Learn Hoisting in Javascript

In this blog post, you will learn about Hoisting in Javascript. Hoisting means all the functions and variable declarations are moved to the top of the program before execution. Let us see a quick example to understand Hoisting better.

a = 6;
console.log(a);
var a;

What do you think is the output of the above code?

It will print "6" in the console without throwing any error. The actual reason is that Javascript will put all the declarations in the memory during the compile phase itself. So the code will work in the below flow:

var a;
a = 6;
console.log(a);

Only Declarations are Hoisted, Initialization is not:

It is important to remember that Javascript will only hoist or move the declarations to the top of the program, initialization will follow in the same program flow. Example:

console.log(a);
var a = 6;

On executing the above example, we will get the undefined error. Let us look at the program flow,

Functions declarations are also Hoisted:

Javascript performs hoisting for function definitions too. Function declarations are also stored in memory during the compile phase. Example:

abc();
function abc(){
    console.log("Code is executed");
}

On executing the above program, we will obtain the output as "Code is executed" printed in the console without any errors. It is because Javascript will move the function declaration part to the top as follows:

function abc(){
    console.log("Code is executed");
}
abc();