eval(), but often it can be mis-used, especially by novice programmers.
But why get rid of it?
- Security. Running
eval()on shared code can be a vector for injection attacks.
- Portability. Code with
eval()included cannot be included by default in a Mozilla app, for example. (cite)
- Debugging. It's tricky to find the code that's going wrong without line numbers.
Okay, it's bad. How do I get rid of it?
Often time, code in an
eval() function can be refactored. For example, you'll often see snippets of code like:
var p = eval("obj." + propertyName);
In fact, this can be accomplished without invoking
eval() at all:
var p = obj[propertyName];
Square brackets can help in more complex cases.
Similarly, be careful passing function names and variable names around as strings. For example, instead of invoking setTimeout() like this:
Lastly, don't parse JSON using
JSON.parse or another more secure alternative. In this circumstance,
eval() is overkill.
eval() is always bad?
eval() is inherently good or bad, but if not used properly it can easily lead to unintended consequences. Often, there is a way to accomplish the same goal faster and more securely without using
eval(), which is why its use is discouraged in general