The "new Function" Syntax in JavaScript

The "new Function" Syntax in JavaScript

The "new Function" Syntax in JavaScript

In JavaScript, the new Function syntax allows you to create functions dynamically using a string. This is useful when the function definition is not known in advance and needs to be created at runtime.

šŸ”¹ Syntax

let func = new Function([arg1, arg2, ...], "function body");
  • The last argument is always the function body (a string).
  • The previous arguments are the parameter names (as strings).

šŸ”¹ Example: Creating a Function Dynamically

let sum = new Function("a", "b", "return a + b"); console.log(sum(5, 7)); // Output: 12

✔ The function is created at runtime using a string.
✔ The parameters "a" and "b" are passed as strings.
✔ The function body is also a string ("return a + b").

šŸ”¹ When to Use new Function?

1️⃣ Creating Functions from Strings (Dynamic Function Creation)

If function logic is stored in a string (e.g., from a server or user input), new Function can be useful.

let formula = "x * 2"; let double = new Function("x", `return ${formula};`); console.log(double(10)); // Output: 20

2️⃣ Parsing JSON-Like Data

let strFunction = `{ return a * b; }`; let multiply = new Function("a", "b", strFunction); console.log(multiply(3, 4)); // Output: 12

✔ This is useful when receiving function logic as a string (e.g., from APIs).

šŸ”¹ new Function vs Regular Function

new Function is Created in Global Scope

Unlike function expressions, functions created using new Function don’t inherit variables from the surrounding scope.

function test() { let a = 10; let func = new Function("return a;"); console.log(func()); // ❌ Error: a is not defined } test();

Why?

  • new Function always creates the function in the global scope.
  • It does not have access to outer variables (unlike closures).

Regular function expressions, on the other hand, do capture outer variables:

function test() { let a = 10; let func = function() { return a; }; console.log(func()); // ✅ Output: 10 } test();

šŸ”¹ Security Risks of new Function

Since new Function executes strings as JavaScript code, it can be a security risk if handling untrusted input.

let userInput = "console.log('Hacked!');"; let hack = new Function(userInput); hack(); // ⚠️ Output: Hacked!

⚠️ Never use new Function with user-generated content!

šŸŽÆ Summary

new Function("arg1", "arg2", "function body") creates a function dynamically.
✔ It does not capture surrounding variables (global scope only).
✔ Useful for dynamic function creation (e.g., parsing strings, executing formulas).
✔ ⚠️ Avoid using new Function with untrusted data (security risk).

šŸš€ When used correctly, new Function can be a powerful tool! Let me know if you need more examples. 😊

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close