'Eval is evil'.
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.
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.