Eval is not evil. Not thinking is evil.

I am sick of hearing the phrase ‘eval is evil’ – It is one of the most overused and inaccurate statements concerning JavaScript. The phrase has become so widespread that people tend to not question it – The sheer number of blogs which just stupidly repeat the phrase is staggering.

So I’m going to say it here; eval is NOT evil. Not thinking is what’s evil. While you should never pass user input to eval, there are safe, useful things that you can do with it.

For example, one of the coolest things that you can do with eval is execute scripts which you loaded dynamically using AJAX – This functionality gives you a great deal of control over how scripts are loaded and when they are executed and it even lets you track a script’s download progress. Because the eval’d content is not user input, this use case is as safe as directly embedding the script into the DOM using a script tag – Just make sure that you use //@ sourceURL = … within the eval’d code to make sure that it is easy to debug (this can be done programmatically by appending //@ sourceURL = … to the source code string before passing it to eval).