You have been referred to this item:

Why eval() is Evil.


In JavaScript, the eval() function evaluates a string as code. This involves re-compilation and interpretation of the code at runtime, which is inefficient and is most often not the best design decision.

The only valid use case for the eval() function is when entirely new code needs to be interpreted, such as from a raw JS server response. Even in this case, the code should only be interpreted once and stored off (with function references or something of the sort) for repeated execution.

Related Evils


setTimeout(), contrary to what MSDN or some other tutorial site will tell you, does not take a string as its first argument, but rather it takes a function reference. Yes, giving it a string as its first argument works in some browsers, but this is only for legacy support and employs the same methods of the eval() function, making it every bit as wrong and unsavory.

One thing you must keep in mind when using a function reference as the first argument to setTimeout() is that any variables that exist in an anonymous function passed to setTimeout() will be evaluated at execution time, not at creation time. See: Closures.

new Function(...)

When you want to create a new function in JS, you should use a function literal:

function() { ... } or function myfunc() { ... }

You can name the function or immediately save off a reference to it into a variable, so there's absolutely no use for the new Function(...) construct. This of course uses the same method as eval() and so all of the above still applies.

See Also

Efficient JavaScript

Eric Lippert: Eval is Evil - Part One, Part Two.