I have an application script that is working correctly, but I have a few eval() statements in order to make things work. I don’t really understand why “eval is evil”, as I keep reading, but what I really don’t understand is how to avoid using it when it’s the only thing that does what I need it to do.
In my script, I have a bunch of products. Each product has its own array of properties. There is also an array of all of the array names. As I run through different functions, these arrays are used to build the page content. The only method I found that works was to do this:
var schedule = {};
$.each(productNameArray, function (i, name) {
schedule = eval(name);
// DO STUFF
});
Simply using name passes a string and does not read the actual array it is meant to reference. Eval makes it work as an object.
So how do accomplish this without using eval()?
What you are doing is parsing a JSON (like) string. That is one of the few cases, where
evalactually isn’tevil.If you can trust the server 100% from which the data arrives at the client, it’s not a real problem at all (talking about security issues with eval).
If that is not the case, you always should avoid using
eval()since any code that is evaluated has access to yourglobal window object,cookies,DOMetc. and be used to spy & send data around.The second big topic about why eval is evil is performance.
eval()is slow when it comes to actually interpret ECMAscript code. Thats for example, usingsetTimeoutlikeThis should always be written like
Letting Javascript parse Javascript, has a big performance impact.