JavaScript Variable Hoisting

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 and const (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 !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.