Maybe you have heard that "eval is evil?" If you haven't take a few minutes to read eval() isn’t evil, just misunderstood.

Without going deep into it, reasons for not using eval are:

  • Security
  • Performance
  • Debugging can be tricky
  • General misuse

As an alternative to eval, the Function constructor can be used to run Js from a string. The following codepen uses it to add a click event to the button.

See the Pen Execute JS in String by James (@jamcgrath) on CodePen.

What is happening is that the constructor is dynamically creating a function that runs only in the global scope. However it still suffers from some issues that eval has such as security and performance, but faster. This can be confirmed by doing this new Function() vs eval() test Also because the code is a string it may prevent some JS engine optimizations.

new Function([arg1, arg2, ...argN], functionBody);

The code block above is the syntax of the Function constructor. It takes strings as it's parameters. The arg parameters are passed to the functionBody. The arguments for the functionBody can be writtern as 'arg1', 'arg2' or 'arg1, arg2' or as 'arg1 , arg2'.

The next codeblock logs to the console the multiplication of two numbers.

const f = new Function("a", "b", "return console.log(a * b)");
f(10, 10); //100

For more information check out these links:

Function constructor at MDN

The "new Function" syntax at javascript.info