This is because you declared a local variable with the same name - and it masks the global variable. Therefore, when you write foo , you are referencing a local variable. This is true, even if you write it before declaring this local variable, the variables in JavaScript are functional. However, you can use the fact that global variables are properties of a global object ( window ):
var foo = window.foo || "";
window.foo here refers to a global variable.
source share