It is called "hoisting" in JavaScript. Your function is automatically transformed into this one:
var a = 1;
function test() {
var a;
alert(a);
a = 2;
alert(a);
}
test();
Nice read about that: http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-javascript-hoisting-explained/