JavaScript’s EVAL’s Secret Feature

If you are not familiar yet with JavaScript’s eval method let’s take a look at what it does

The argument of the eval function is a string. If the string represents an expression, eval evaluates the expression. If the argument represents one or more JavaScript statements, eval evaluates the statements.

Here are a couple of common uses for eval:

var x = 2;
var y = 39;
var z = "42";
eval("x + y + 1"); // returns 42
eval(z);           // returns 42

So as you can see the eval method can be quite useful. However, there are quite a few reasons you shouldn’t use it unless you have to:

  1. eval is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension. More importantly, third party code can see the scope in which eval was invoked, which can lead to possible attacks in ways to which the similar Function is not susceptible.
  2. eval is also generally slower than the alternatives, since it has to invoke the JS interpreter, while many other constructs are optimized by modern JS engines.

Despite these warnings there has been one particular situation in which I have found the eval method particularly useful, and that has been converting strings into JavaScript objects. Whenever possible I recommend using JSON’s functions, but there have been several times where I had to convert a string that was valid JavaScript but not valid JSON. When you come across a situation in which JSON.parse is not working despite having a string which is valid JavaScript then eval should be your next choice.

Paulo Diniz