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:
- 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.
- 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.