adam barnhard

The case against eval


“eval is Evil: The eval function is the most misused feature of JavaScript.
Avoid it”
Douglas Crockford in JavaScript: The Good Parts


The case against eval() generally centers around safety. It is always a terrible idea to intentionally allow your programs to execute code you didn’t write or can’t validate the source or intent of.

The question then, is that if a string isn’t generated by a user, is eval ok to use?

The answer is no; though the reason isn’t safety, but performance.

JavaScript engines have a number of performance optimizations they can employ during the compilation phase. Some of reduce to the ability to analyze the code as it lexes and pre‐determine where all the declarations are, so that resolving identifiers during execution takes less effort.

If the engine finds an eval(...) statement in the code, it effectively has to assume that all the pre-execution identifier location information it has might be invalid, since it can’t know if, at run time, the code passed to eval(...) will modify a given lexical scope. Since most of the optimizations it would make would be pointless if eval(...) modified a scope, the compiler simply doesn’t perform the optimizations at all.

This problem is not unique to eval, with (and its function of creating new lexical scopes based on the object properties passed to it) causes the same problem and results in the code not being optimized.

The only way around the problem, if you simply cannot avoid using eval, is to isolate that code in a separate file that can be loaded and compiled separately from the rest of the application code.


Share this: