In the first case, you havn't created any local variable but accessed the test defined from the global scope.
var test = 1; // Global Test - GT
function scope() {
alert(test); // Accesses GT
test = 2; // Assigns to GT
}
scope();
alert(test); // Accesses GT
But in the second case, you are creating a new variable, but accessing it before assigning a value it. By default, all the unassigned variables will have undefined.
In JavaScript, variables are scoped to the functions in which they are declared. So, when you use var variable_name in a function, you are creating new variable and it will be accessible to all parts of the function. Also, you are creating a variable with the same name as the global variable. When JavaScript looks up for the variable test, it will first search the local scope of the function and it will be found there. So, local test variable will be used.
alert(test); // value will be `undefined` till a value is assigned.
var test = 2; // Declared a new variable and assigned value here
This behavior is called variable hoisting.