From zero to code hero

Just another page about javaScript, me, cats and general programming things.

When `eval` is your friend

'Eval is evil'.

If you've started your adventure with JavaScript in the last few years you probably came across this quote. And partially because of that you might've never used eval for anything. The longer version of the statement (which you can find in Douglas Crockford's 'JavaScript: The Good Parts') is as follows :

“eval is Evil. (...) The eval function is the most misused feature of JavaScript. Avoid it”

Just to bring few of the arguments leveled against using eval :

  • Malicious code can easily be executed when using eval
  • It requires compilation so it's slow
  • It's hard (and until not long ago it was impossible) to debug
  • It inherits context of the scope it was invoked in

Few years ago Nicolas Zakas wrote an article debunking some of them, and explaining details behind the rest. So I strongly recommend reading it.

In my personal opinion, if you understand how JavaScript and it's compiler work, you're golden. And often can find some cool ways of using eval to your purposes. I, for instance like to use it to dynamically build regular expressions. Some time ago I had to write a function that checked for existence of different pairs of brackets in a string. So for instance this code :


would return true, because it contains both opening ( and closing ) brackets, while this one:


would return false, because the closing > is missing.
Here's the runnable code on jsfiddle, and explanation below:

So in the body of my verify function I first define two arrays (with equal lengths) of opening and matching closing brackets. Then we iterate over openingBrackets list and check if the string thet we're testing contains either opening or closing character. If either of that is true, we create a new regular expression. Here's the place where eval comes into play. Thanks to it I can dynamically create a RegExp object looking for the opening sign, then any string until the closing expression is found.
Last thing that's left is to test the string with our newly created RegExp.

I hope that with this short example I was able to show you how powerfull and usefull eval can be if you know how to use it. If you want to know more about how this function works, read the article linked above or/and the best resource on the net - Mozilla's MDN.