what does eval do and why its evil? [duplicate]

eval() takes the string it is given, and runs it as if it were plain JavaScript code.

It is considered “evil” because:

  • It over-complicates things – Most cases where eval() is used, there would be a much simpler solution that didn’t require it. This example in the question is a perfect case in point: there is absolutely no need for eval() for an expression like this. JS has perfectly good syntax for referencing an object property name as a string (myObject["x"] is the same as myObject.x).

  • It’s much harder to debug – It’s harder to work with it in a debugger, and even once you have managed to work out what’s going on, you have you extra work to do because you have to debug both the eval’d code, and the code that generated the original string to eval.

  • It slows things down – The script compiler cannot pre-compile code in an eval(), because it doesn’t know what the code will contain until it gets there. So you lose out on a some of the performance benefits in modern Javascript engines.

  • It is a hacker’s dream – eval() runs a string as code. Hackers love this because it’s much easier to inject a string into a program than to inject code; but eval() means you can inject a string, and get it to run as code. So eval() makes your code easier to hack. (this is less of an issue for browser-based Javascript than other languages, as JS code is accessible in the browser anyway, so your security model should not be based on your code being immutable, but nevertheless, injection hacks can still be a problem, particularly with cross-site attacks).

Leave a Comment