If I defined some variable in outer closure, and in the inner closure has defined another variable with the same name. Can I somehow get the outer variable?
I know it's still somewhere in the memory and not been overwritten since it can be printed after the function. Is there a way to access it?
const foo = 'outer';
function bar() {
const foo = 'inner';
// Is there a way to get the outside foo from here?
console.log(foo); // "inner", but I want it to be "outer"
}
bar();
console.log(foo); // "outer"
I thought I'd add this answer since it might help in some situations.
If
foo
is on the top level and declared withconst
, one of the only ways to access it withnew Function
, whose scope when run is on the top level. (Please don't actually do this):See comment by Hao below.
eval
can work too, but it's a bit more complicated. As MDN says:So if you reference
eval
by any method other than calling the standalone variable nameeval(arg)
, the code will run on the top level, and it will be able to see the variable on the top level:If
foo
is declared withvar
instead ofconst
, you can just access that property of the global object:If the shadowed variable is not on the top level, eg
Then there's no way to access the
intermediate
variable from themore code here
section.