1

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.
1

1 Answer 1

1

When you use the new Function constructor in JavaScript, the function you create does not form a closure over the local variables of its surrounding scope. Instead, functions created with new Function are always executed in the global scope.

This will give the result you're expecting

return function() { return x; };

function outer() {
  let x = 10;
  return function() {
    return x;
  };
}

const fn = outer();
console.log(fn()); // 10
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.