Getting rid of eval() in your JavaScript

 

eval() is a popular JavaScript function. Sometimes it's totally appropriate to use 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:

setTimeout("myBeautifulFunction()", 5000);

Remember that in JavaScript, you can pass functions by their identifiers:

setTimeout(myBeautifulFunction, 5000);

Lastly, don't parse JSON using eval(). Use JSON.parse or another more secure alternative. In this circumstance, eval() is overkill.

So eval() is always bad?

Nothing about 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

Did you enjoy this post? Please spread the word.