Variable hoisting in JavaScript means to move all variable declarations to top of function. This means that if we declare a variable at the end of a function, the runtime will hoist it to the top and we will not have any error if we would have used that variable before being declared.
Please note that variables declared with the
var
keyword are subject to hoisting.let
andconst
(introduced in ES6) does not have hoisting effect.
What hoisting means?
As said before, hoisting means moving variable declarations to top. It is important to note that hoisting does not happen if you initialize the variable.
Variable declaration (Hoisting happen)
In below code, data
is used before it is declared.
function fun() { data = 1; console.log(data); //Outputs 1 var data; } fun();
At runtime, after hoisting above code will look like this:
function fun() { var data; /*** moved to top ***/ data = 1; console.log(data); //Outputs 1 } fun();
Variable initialization (Hoisting does NOT happen)
In below code, data
is declared as well as initialized also. In this case, hoisting will happen and it will not move upto top. So value of data
will be available only after it is declared and initialized; not before.
function fun() { console.log(data); //Outputs 'undefined' var data = 1; console.log(data); //Outputs 1 } fun();
Drop me your questions related to variable hoisting in javascript in comments section.
Happy Learning !!