This is because in JavaScript, variables get hoisted, which means
Variables are initialised to undefined when created. A variable with
an Initialiser is assigned the value of its AssignmentExpression when
the VariableStatement is executed, not when the variable is created.(ES5 §12.2)
Thus, semantically, your code would be equivalent, to the following...
var foo = "hello";
function fxn(){
var foo; //Variables are initialised to undefined when created
alert(foo);
foo = "test"; //A variable with an *Initialiser* is assigned the value of its *AssignmentExpression* when the *VariableStatement* is **executed**
}
fxn();