JavaScript Hoisting : Variable Initialization

In JavaScript, Variable Initialization always takes precedence. Even, Function objects are created for all Function Declarations and got assigned to Global Objects. For ex. look at the following code: 

var x = 500;
function check() {
if (typeof(x) === 'undefined') {
  var x = 100;


The above code will give 3 alert messages with the response as 100, 100, & 500


Actually, this is how the code is getting compiled.

/* x is already defined and assigned with value 5 and is available in 
   the Global scope. */
var x=500;

function check( ) {
	// variable x get hoisted to the top.
	var x;
	if (typeof(x) === 'undefined') {  
		//therefore, here it will be undefined.
		//assigning value 100
		x = 100;
		//x will be 100
	// x will be 100 , value of x will be 100 inside the function scope.


/* here the value of x will be still 500. Since it has its own value available in 
   the global scope.*/

As you can see, x has both a Global as well as a local declaration. Now even though the local variable x is declared inside the if loop, at the time of execution, when the method check is called, first all the variables of that function (in this case only x) gets declared. So x is declared (not defined) even before the if loop, & when the condition matches, 100 is then assigned to the local variable x. However, the scope of this 100 lies within the function only and so, when an alert is raised in the last line, it will display 500 (Value of the Globally declared variable x).


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.