Why is using the JavaScript eval function a bad idea?

  1. Home
  2. javascript
  3. Why is using the JavaScript eval function a bad idea?

The eval function is a powerful and easy way to dynamically generate code, so what are the caveats?

First answer

  1. Improper use of eval opens up your
    code for injection attacks

  2. Debugging can be more challenging
    (no line numbers, etc.)

  3. eval’d code executes slower (no opportunity to compile/cache eval’d code)

Edit: As @Jeff Walden points out in comments, #3 is less true today than it was in 2008. However, while some caching of compiled scripts may happen this will only be limited to scripts that are eval’d repeated with no modification. A more likely scenario is that you are eval’ing scripts that have undergone slight modification each time and as such could not be cached. Let’s just say that SOME eval’d code executes more slowly.

Second answer

I believe it’s because it can execute any JavaScript function from a string. Using it makes it easier for people to inject rogue code into the application.

Third answer

Two points come to mind:

  1. Security (but as long as you generate the string to be evaluated yourself, this might be a non-issue)

  2. Performance: until the code to be executed is unknown, it cannot be optimized. (about javascript and performance, certainly Steve Yegge’s presentation)

Reprint:https://stackoverflow.com/questions/86513/why-is-using-the-javascript-eval-function-a-bad-idea
Spread the love

Related articles

Comments are closed.