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.