Here are 2 javascript functions
var a = 10;
function abcd()
{
alert(a);//alerts 10
a=5;
}
And another code is this
var a = 10;
function abcd()
{
alert(a);//alerts undefined
var a=5;
}
In both function assignment/declaration is after alert() call.
Then why alert message are 10
and undefined
respectively?
That's because your variable gets "hoisted" up of its containing scope by the interpreter when you declare it. So your code ends up being interpreted like this:
function abcd()
{
var a;
alert(a); //alerts undefined
a = 5;
}
To avoid this kind of confusion, you can follow some practices that will keep things in place, like declaring your local-scoped (that is, variables declared with the keyword var
inside a function scope) variables right in the beginning of the function.
Note that, as you can read from the article, this happens with nested functions aswell.