05. Function Constructor

The Function constructor creates a new Function object. Calling the constructor directly can create functions dynamically, but suffers from security and performance issues similar to eval.

Expression new Function(arg1, arg2, ..., argN, bodyString) creates a new function:

  • The arguments arg1, args2, ..., argN passed to constructor become the parameter names for the new function

  • the last argument bodyString is used as the function body code.

const fn = new Function("x", "y", "return x ** y;");
fn(2, 2); // => 4

The functions created this way don't have access to current scope, thus closures cannot be created. They are always created in the global scope. One possible application of new Function is a better way to access the global object in a browser or NodeJS script:

(function() {
  "use strict";
  var global = new Function("return this")();
  console.log(global === window); // => true
  console.log(this === window); // => false
})();

Important to remember about new Function is that almost never functions should be declared this way. Because the function body is evaluated on runtime, this approach inherits many eval() usage problems: security risks, harder debugging, no way to apply interpreter optimizations, no code auto-complete.

Last updated