Why eval() is evil

If there was one function that was truly loathed by Javascript Developers, eval() would be an easy winner. And for a good reason. A lot has been written about eval() and people have gone into great detail why the function should be avoided at all times (and a few contrarians have tried to defend it…mugs). However, I will not try to rewrite what a five second google-search can explain. I will use a simple example because those seem to drive the point home.

Let’s assume you have a little secret you want to keep away from a user (although if you use front-end environment to keep secrets, you’re not really good at this secret business). You secret happens to be 'It's a little secret'. You store this secret in a creatively named variable, myLittleSecret. You forget about this secret and write another function to evaluate what the user inputs.

  function givethBackToUser(){
    var userInput = prompt('Give us something and we will return it; we promise!');
    eval('alert("We returned: "'+userInput+')');

In the above example, an alert box will return with whatever the user input was. Unless the user happens to assign myLittleSecret as their input. Instead of returning myLittleSecret as a string, it assigns the value of myLittleSecret to userInput. Which means, the user will see   We returned: "It's a little secret". In the end it won’t be a little secret after all.

There is a lot more harm that can happen when using eval(). The main point is that everything you can do with it, can be done differently and efficiently. There is just too much that can go wrong when you are at the mercy of your users.