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)); // 5This 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)); // 10The 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:
- Creates a new function in the global scope (not in the local one!).
- Parses the string with the body as regular JavaScript code.
- 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 definedExplanation:
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)); // 15Why 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
| Scenario | Why use it |
|---|---|
| Generating functions "on the fly" | When the function body is not known in advance |
| Interpreter, template engine, DSL | For example, processing user-defined expressions |
| Testing derived expressions | Quickly creating computed functions |
Summary
| Feature | Description |
|---|---|
| Creates a function from a string | Yes |
| Scope | Global, no access to outer variables |
| Safety | Potentially dangerous (like eval) |
| Performance | Slow, because it parses code at runtime |
| Closures | Not supported |
| Use case | Dynamic creation of computed functions |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.