Skip to main content

JavaScript : What is Javascript Hoisting

What is Hoisting in Javascript ??

In Javascript the variable declaration can be done at any place inside the function or inside the script. Where a variable is declared makes no difference because the javascript interpreter always move the variable declarations silently to the top of the scope where the variable is used.
For example, everyone will be fine the following javascript code.

<script>
var num;
num = 5;

function foo(){
alert(num);
}
foo();
</script>

And, all will be able to guess that the function foo() will alert value 5.
However, the following code will confuse a lot of the developers, since the variable num is used before it is declared.

<script>
num = 5;

function foo(){
alert(num);
}

foo();
var num;
</script>

The above code will run absolutely fine and will alert 5 just as in the previous example.
So what happened in example 2 ? What happened is Javascript Hoisting and it happened automatically behind the scenes.
As stated earlier, The javascript interpreter moved the declaration of the variable num to the top not the initialization, so the code becomes



var num;
num = 5;

function foo(){
alert(num);
}

foo();


Note :: javascript hoisting only moves declarations to top but not initialization to top.
What above statement means is that
  
function foo(){
alert(num);
}
foo();

var num = 5;

The above code will alert undefined, instead of 5, this is because only the declaration is hoisted and not initialization. The above code as read bu interpreter is as follows

  
var num;

function foo(){
alert(num);
}
foo();

num = 5;
So it is very important to keep this in mind while writing your javascript code.

Comments