title: JavaScript function closure value lost
body: <p><strong>Closure</strong> values get <strong>lost</strong> in a function passed as a <strong>callback</strong> to another function defined by <code>new Function()</code> method.</p>
  <h3>Code</h3>
  <p>How can the function <code>baz()</code> be fixed to <strong>access the closure values</strong> in the <strong>callback</strong>?</p>
  <p><strong>Note:</strong> The function <code>foo()</code> cannot be modified.</p>
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>const foo = () =&gt; {
    const b = 2;
  
    return (a) =&gt; {
      return a + b; // unable to access `b` here
    };
  };
  
  const bar = (a = 1, callback = foo()) =&gt; 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</code></pre>
  </div>
  </div>
  </p>