Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

180
Views
JavaScript function closure value lost

Closure values get lost in a function passed as a callback to another function defined by new Function() method.

Code

How can the function baz() be fixed to access the closure values in the callback?

Note: The function foo() cannot be modified.

const foo = () => {
  const b = 2;

  return (a) => {
    return a + b; // unable to access `b` here
  };
};

const bar = (a = 1, callback = foo()) => callback(a);

const baz = new Function(["a = 1", `callback = ${foo()}`], "return callback(a)");

console.log(bar(1)); // works fine and prints 3
console.log(baz(1)); // throws Uncaught ReferenceError: b is not defined

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Don't use string interpolation with a function. What is happening can be seen here:

const foo = () => {
  const b = 2;
  return (a) => a+b;
};
console.log(new Function(["a = 1", `callback = ${foo()}`], "return callback(a)"))

The function (a) => a+b gets converted to a string, which is then put in the source code of the new function. Yes, this looses the closure - it looses the entire function object.

Instead, just write

const foo = () => {
  const b = 2;
  return (a) => a+b;
};
const bar = function(a = 1, callback = foo()) { return callback(a); };
const baz = new Function(["a = 1", "callback = foo()"], "return callback(a)");

console.log(bar(1));
console.log(baz(1));
console.log(bar);
console.log(baz);

As you can see from the logged functions, their code is now equivalent - and since everything in the demo snippet is global, they also work the same.

It's a bit different when foo (or anything else you want to access from the function code string) is defined in a local scope. In that case, you'll need to use a trick like this to explicitly make the value available to the dynamically generated code.

about 4 years ago · Juan Pablo Isaza Report

0

I believe that Function constructors only execute within the global scope and do no create closures. This answer may help you:

Function Constructor MDN

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!