I was experimenting with closures in JavaScript and ran into something confusing.
function outer() {
let x = 10;
return new Function("return x;");
}
const fn = outer();
console.log(fn());
I expected this to print 10, because fn is returned from outer and should "remember" the local variable x (normal closure behavior).
But instead, I get:
ReferenceError: x is not defined
My understanding
- Normally, if I returned a nested function, it would form a closure and capture x.
- But when I use new Function, it doesn’t seem to have access to outer’s scope at all.
xisn't in the global scope.