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?
A program can have the same name for local and global variables but the value of a local variable inside a function will take preference. For accessing the global variable with same rame, you'll have to use the scope resolution operator.
What happens if a local variable exists with the same name as the global variable you want to access? Explanation: If a local variable exists with the same name as the local variable that you want to access, then the global variable is shadowed. That is, preference is given to the local variable.
Python allows the declaration of Local variable with the same name as Global variable.
LOCAL variables are only accessible in the function itself. So, in layman's terms, the GLOBAL variable would supersede the LOCAL variable in your FIRST code above.
That's because you declared a local variable with the same name - and it masks the global variable. So when you write foo
you 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
):
var foo = window.foo || "";
window.foo
refers to the global variable here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With