eval()
executes a string of characters as code. You use eval()
precisely because the string contents are not known in advance, or even generated server-side; basically, you need eval()
because the JavaScript itself will generate the string from data which is available only dynamically, in the client.
Thus, eval()
makes sense in situations where the JavaScript code will generate code. This is not intrinsically evil, but it is hard to do securely. Programming languages are designed to allow a human being to write instructions that a computer understands; to that effect, any language is full of small quirks and special behaviours that are supposed to help the human programmer (e.g. the automatic adding of ';' at the end of some statements in JavaScript). This is all nice and dandy for "normal" programming; but when you generate code from another program, based on data which may be potentially hostile (e.g. string excerpt from other site users), then you have to, as the developer for the code generator, know about all these quirks, and prevent hostile data to exploit them in damaging ways.
In that sense, code generators (and thus eval()
) incur the same conceptual issues as raw SQL and its consequence, SQL injection attacks. Assembling at runtime an SQL request from externally provided parameters can be done securely, but this requires minding an awful lot of details, so the usual advice is not to do that. This relates to the usual conundrum of security, i.e. that it is not testable: you can test whether some piece of code works properly on correct data, but not that it never works improperly on incorrect data. Similarly, using eval()
securely is possible, but it is so hard in practice that it is discouraged.
All of this is said in all generality. In your specific context, eval()
might be safe. However, it takes some effort to have a context safe for use of eval()
, that actually needs eval()
.