Eval is an evil problem

Using JSlint to test my javascript.

I get an error is eval is evil! Why is this an alternative that I can use?

Here is an example of where I am using eval and would like a workaround for it.

I have an array like this:

var Resources = { message_1: 'Message 1', message_2: 'Message 2', message_3: 'Message 3', message_4: 'Message 4' }; 

I have a function (functionResult) that returns a number, either 1, 2, 3, or 4. So, what I want to do in the next line of code is to get a resource in an array that ends there as a result of my function.

 $('#divPresenter').html(eval($.validator.format('Resources.message_{0}', functionResult))); 

Any ideas on how I can remove eval and replace with something else?

+4
source share
6 answers

Instead:

 eval($.validator.format('Resources.message_{0}', functionResult)) 

just use:

 Resources["message_" + functionResult] 

All objects in JavaScript are truly associative arrays (aka hashes), and the point syntax ( ab ) is just syntactic sugar for finding something in the hash ( a['b'] ). Therefore, you do not need eval at all; just create the key as a string and see your value with this key.

+9
source

http://blogs.msdn.com/b/ericlippert/archive/2003/11/01/53329.aspx

In most cases, eval is used as a sledgehammer hitting a fly - it does its job, but also has a lot of power. It is slow, it is bulky, and tends to increase damage when you make a mistake.

+8
source

This is evil because it allows you to execute a string as code, and who knows where the string comes from or what it contains.

And yes, 99.9% of the time, there are better alternatives (what exactly they depend on what you use eval for). The remaining 0.1% of the time, you really have no choice but to use eval , and in such cases you need to be very careful.

+5
source

JS Lint includes what Douglas Crockford considers best practice for JavaScript. One of the functions that he strongly discourages using is eval . I think he considers it slow and insecure.

There may be many potential alternatives depending on the code. If you want to publish a section of your code that uses eval , we can give more specific advice.

+3
source

If you are trying to use eval to turn strings into JSON objects, maybe try the JSON parser lib (I never used it, but it looks reasonable).

+3
source

I don’t quite understand what you are doing, but it looks like $('#divPresenter').html(eval($.validator.format('Resources.message_{0}', functionResult)));
can be written as $('#divPresenter').html(Resources["message_" + functionResult]);

+2
source

All Articles