Code from a String

This is a rare but powerful way to create a function from text.

let sum = new Function('a', 'b', 'return a + b');
alert( sum(1, 2) ); // 3

What's the catch?

Such functions do not have access to the outer variables (closure) of their birthplace. They only see global variables.

When to use this?

  • When you receive function code from a server as a string.
  • In complex templating engines.
Caution

Using new Function (like eval) can be a security risk if the strings come from users. Hackers could inject malicious code!