Skip to main content

Function Constructor

What it is

Function Constructor is a special way of creating functions "on the fly" from strings. It lets you dynamically create a new Function object with given parameters and a function body.

Syntax:

javascript
new Function ([arg1, arg2, ...argN], functionBody)
  • arg1...argN - the function's parameter names (strings)
  • functionBody - a string with the function body code

Usage examples

Example 1: the simplest function

javascript
const sum = new Function('a', 'b', 'return a + b;'); console.log(sum(2, 3)); // 5

This is equivalent to:

javascript
function sum(a, b) { return a + b; }

but it is created at runtime.


Example 2: creating a function from a string

javascript
const expr = 'return x * 2;'; const double = new Function('x', expr); console.log(double(5)); // 10

The function is formed dynamically, as if it were interpreted as new JS code.


How it works "under the hood"

When you call new Function(...), the JavaScript engine:

  1. Creates a new function in the global scope (not in the local one!).
  2. Parses the string with the body as regular JavaScript code.
  3. Returns a function object ready to be called.

Important: new Function has no access to outer variables

Error:

javascript
let x = 10; const fn = new Function('return x;'); console.log(fn()); // ReferenceError: x is not defined

Explanation:

Functions created via new Function always run in the global scope, so they cannot "see" lexical variables from closures.


Example of correct usage

It can be used when you need to run dynamically composed code:

javascript
const operation = '+'; const makeOp = new Function('a', 'b', `return a ${operation} b;`); console.log(makeOp(10, 5)); // 15

Why it is better not to overuse it

new Function effectively works like eval():

  • it runs the string as JavaScript code;
  • it is unsafe (if the string comes from outside);
  • it is slower, because it requires parsing and compilation at runtime;
  • it loses context and closures.

When it can be useful

ScenarioWhy use it
Generating functions "on the fly"When the function body is not known in advance
Interpreter, template engine, DSLFor example, processing user-defined expressions
Testing derived expressionsQuickly creating computed functions

Summary

FeatureDescription
Creates a function from a stringYes
ScopeGlobal, no access to outer variables
SafetyPotentially dangerous (like eval)
PerformanceSlow, because it parses code at runtime
ClosuresNot supported
Use caseDynamic creation of computed functions

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.