You are hiding the global variable myColor with a local variable of the same name. Remove the var keyword from the function to see the global variable.
var myColor = "blue"; function sayColor() { alert(myColor); myColor = "green";
Javascript has only the scope of the function, and all the variables declared inside the function go up so that they are available throughout the function. The first warning in the original OP version used an uninitialized, raised, local variable, so it printed undefined .
source share