foo = "foobar";
var bar = function(){
var foo = foo || "";
return foo;
}
bar();`
This code gives a result empty string. Why cannot JS reassign a local variable with same name as a global variable? In other programming languages the expected result is of course “foobar”, why does JS behave like that?
That’s because you declared a local variable with the same name – and it masks the global variable. So when you write
fooyou refer to the local variable. That’s true even if you write it before the declaration of that local variable, variables in JavaScript are function-scoped. However, you can use the fact that global variables are properties of the global object (window):window.foorefers to the global variable here.