Related
The eval function is a powerful and easy way to dynamically generate code, so what are the caveats?
Improper use of eval opens up your
code for injection attacks
Debugging can be more challenging
(no line numbers, etc.)
eval'd code executes slower (no opportunity to compile/cache eval'd code)
Edit: As #Jeff Walden points out in comments, #3 is less true today than it was in 2008. However, while some caching of compiled scripts may happen this will only be limited to scripts that are eval'd repeated with no modification. A more likely scenario is that you are eval'ing scripts that have undergone slight modification each time and as such could not be cached. Let's just say that SOME eval'd code executes more slowly.
eval isn't always evil. There are times where it's perfectly appropriate.
However, eval is currently and historically massively over-used by people who don't know what they're doing. That includes people writing JavaScript tutorials, unfortunately, and in some cases this can indeed have security consequences - or, more often, simple bugs. So the more we can do to throw a question mark over eval, the better. Any time you use eval you need to sanity-check what you're doing, because chances are you could be doing it a better, safer, cleaner way.
To give an all-too-typical example, to set the colour of an element with an id stored in the variable 'potato':
eval('document.' + potato + '.style.color = "red"');
If the authors of the kind of code above had a clue about the basics of how JavaScript objects work, they'd have realised that square brackets can be used instead of literal dot-names, obviating the need for eval:
document[potato].style.color = 'red';
...which is much easier to read as well as less potentially buggy.
(But then, someone who /really/ knew what they were doing would say:
document.getElementById(potato).style.color = 'red';
which is more reliable than the dodgy old trick of accessing DOM elements straight out of the document object.)
I believe it's because it can execute any JavaScript function from a string. Using it makes it easier for people to inject rogue code into the application.
It's generally only an issue if you're passing eval user input.
Two points come to mind:
Security (but as long as you generate the string to be evaluated yourself, this might be a non-issue)
Performance: until the code to be executed is unknown, it cannot be optimized. (about javascript and performance, certainly Steve Yegge's presentation)
Passing user input to eval() is a security risk, but also each invocation of eval() creates a new instance of the JavaScript interpreter. This can be a resource hog.
Mainly, it's a lot harder to maintain and debug. It's like a goto. You can use it, but it makes it harder to find problems and harder on the people who may need to make changes later.
One thing to keep in mind is that you can often use eval() to execute code in an otherwise restricted environment - social networking sites that block specific JavaScript functions can sometimes be fooled by breaking them up in an eval block -
eval('al' + 'er' + 't(\'' + 'hi there!' + '\')');
So if you're looking to run some JavaScript code where it might not otherwise be allowed (Myspace, I'm looking at you...) then eval() can be a useful trick.
However, for all the reasons mentioned above, you shouldn't use it for your own code, where you have complete control - it's just not necessary, and better-off relegated to the 'tricky JavaScript hacks' shelf.
Unless you let eval() a dynamic content (through cgi or input), it is as safe and solid as all other JavaScript in your page.
Along with the rest of the answers, I don't think eval statements can have advanced minimization.
It is a possible security risk, it has a different scope of execution, and is quite inefficient, as it creates an entirely new scripting environment for the execution of the code. See here for some more info: eval.
It is quite useful, though, and used with moderation can add a lot of good functionality.
Unless you are 100% sure that the code being evaluated is from a trusted source (usually your own application) then it's a surefire way of exposing your system to a cross-site scripting attack.
It's not necessarily that bad provided you know what context you're using it in.
If your application is using eval() to create an object from some JSON which has come back from an XMLHttpRequest to your own site, created by your trusted server-side code, it's probably not a problem.
Untrusted client-side JavaScript code can't do that much anyway. Provided the thing you're executing eval() on has come from a reasonable source, you're fine.
It greatly reduces your level of confidence about security.
If you want the user to input some logical functions and evaluate for AND the OR then the JavaScript eval function is perfect. I can accept two strings and eval(uate) string1 === string2, etc.
If you spot the use of eval() in your code, remember the mantra “eval() is evil.”
This
function takes an arbitrary string and executes it as JavaScript code. When the code in
question is known beforehand (not determined at runtime), there’s no reason to use
eval().
If the code is dynamically generated at runtime, there’s often a better way to
achieve the goal without eval().
For example, just using square bracket notation to
access dynamic properties is better and simpler:
// antipattern
var property = "name";
alert(eval("obj." + property));
// preferred
var property = "name";
alert(obj[property]);
Using eval() also has security implications, because you might be executing code (for
example coming from the network) that has been tampered with.
This is a common antipattern when dealing with a JSON response from an Ajax request.
In those cases
it’s better to use the browsers’ built-in methods to parse the JSON response to make
sure it’s safe and valid. For browsers that don’t support JSON.parse() natively, you can
use a library from JSON.org.
It’s also important to remember that passing strings to setInterval(), setTimeout(),
and the Function() constructor is, for the most part, similar to using eval() and therefore
should be avoided.
Behind the scenes, JavaScript still has to evaluate and execute
the string you pass as programming code:
// antipatterns
setTimeout("myFunc()", 1000);
setTimeout("myFunc(1, 2, 3)", 1000);
// preferred
setTimeout(myFunc, 1000);
setTimeout(function () {
myFunc(1, 2, 3);
}, 1000);
Using the new Function() constructor is similar to eval() and should be approached
with care. It could be a powerful construct but is often misused.
If you absolutely must
use eval(), you can consider using new Function() instead.
There is a small potential
benefit because the code evaluated in new Function() will be running in a local function
scope, so any variables defined with var in the code being evaluated will not become
globals automatically.
Another way to prevent automatic globals is to wrap the
eval() call into an immediate function.
EDIT: As Benjie's comment suggests, this no longer seems to be the case in chrome v108, it would seem that chrome can now handle garbage collection of evaled scripts.
VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
Garbage collection
The browsers garbage collection has no idea if the code that's eval'ed can be removed from memory so it just keeps it stored until the page is reloaded.
Not too bad if your users are only on your page shortly, but it can be a problem for webapp's.
Here's a script to demo the problem
https://jsfiddle.net/CynderRnAsh/qux1osnw/
document.getElementById("evalLeak").onclick = (e) => {
for(let x = 0; x < 100; x++) {
eval(x.toString());
}
};
Something as simple as the above code causes a small amount of memory to be store until the app dies.
This is worse when the evaled script is a giant function, and called on interval.
Besides the possible security issues if you are executing user-submitted code, most of the time there's a better way that doesn't involve re-parsing the code every time it's executed. Anonymous functions or object properties can replace most uses of eval and are much safer and faster.
This may become more of an issue as the next generation of browsers come out with some flavor of a JavaScript compiler. Code executed via Eval may not perform as well as the rest of your JavaScript against these newer browsers. Someone should do some profiling.
This is one of good articles talking about eval and how it is not an evil:
http://www.nczonline.net/blog/2013/06/25/eval-isnt-evil-just-misunderstood/
I’m not saying you should go run out and start using eval()
everywhere. In fact, there are very few good use cases for running
eval() at all. There are definitely concerns with code clarity,
debugability, and certainly performance that should not be overlooked.
But you shouldn’t be afraid to use it when you have a case where
eval() makes sense. Try not using it first, but don’t let anyone scare
you into thinking your code is more fragile or less secure when eval()
is used appropriately.
eval() is very powerful and can be used to execute a JS statement or evaluate an expression. But the question isn't about the uses of eval() but lets just say some how the string you running with eval() is affected by a malicious party. At the end you will be running malicious code. With power comes great responsibility. So use it wisely is you are using it.
This isn't related much to eval() function but this article has pretty good information:
http://blogs.popart.com/2009/07/javascript-injection-attacks/
If you are looking for the basics of eval() look here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
The JavaScript Engine has a number of performance optimizations that it performs during the compilation phase. Some of these boil down to being able to essentially statically analyze the code as it lexes, and pre-determine where all the variable and function declarations are, so that it takes less effort to resolve identifiers during execution.
But if the Engine finds an eval(..) in the code, it essentially has to assume that all its awareness of identifier location may be invalid, because it cannot know at lexing time exactly what code you may pass to eval(..) to modify the lexical scope, or the contents of the object you may pass to with to create a new lexical scope to be consulted.
In other words, in the pessimistic sense, most of those optimizations it would make are pointless if eval(..) is present, so it simply doesn't perform the optimizations at all.
This explains it all.
Reference :
https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20&%20closures/ch2.md#eval
https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20&%20closures/ch2.md#performance
It's not always a bad idea. Take for example, code generation. I recently wrote a library called Hyperbars which bridges the gap between virtual-dom and handlebars. It does this by parsing a handlebars template and converting it to hyperscript which is subsequently used by virtual-dom. The hyperscript is generated as a string first and before returning it, eval() it to turn it into executable code. I have found eval() in this particular situation the exact opposite of evil.
Basically from
<div>
{{#each names}}
<span>{{this}}</span>
{{/each}}
</div>
To this
(function (state) {
var Runtime = Hyperbars.Runtime;
var context = state;
return h('div', {}, [Runtime.each(context['names'], context, function (context, parent, options) {
return [h('span', {}, [options['#index'], context])]
})])
}.bind({}))
The performance of eval() isn't an issue in a situation like this because you only need to interpret the generated string once and then reuse the executable output many times over.
You can see how the code generation was achieved if you're curious here.
I would go as far as to say that it doesn't really matter if you use eval() in javascript which is run in browsers.*(caveat)
All modern browsers have a developer console where you can execute arbitrary javascript anyway and any semi-smart developer can look at your JS source and put whatever bits of it they need to into the dev console to do what they wish.
*As long as your server endpoints have the correct validation & sanitisation of user supplied values, it should not matter what gets parsed and eval'd in your client side javascript.
If you were to ask if it's suitable to use eval() in PHP however, the answer is NO, unless you whitelist any values which may be passed to your eval statement.
I won't attempt to refute anything said heretofore, but i will offer this use of eval() that (as far as I know) can't be done any other way. There's probably other ways to code this, and probably ways to optimize it, but this is done longhand and without any bells and whistles for clarity sake to illustrate a use of eval that really doesn't have any other alternatives. That is: dynamical (or more accurately) programmically-created object names (as opposed to values).
//Place this in a common/global JS lib:
var NS = function(namespace){
var namespaceParts = String(namespace).split(".");
var namespaceToTest = "";
for(var i = 0; i < namespaceParts.length; i++){
if(i === 0){
namespaceToTest = namespaceParts[i];
}
else{
namespaceToTest = namespaceToTest + "." + namespaceParts[i];
}
if(eval('typeof ' + namespaceToTest) === "undefined"){
eval(namespaceToTest + ' = {}');
}
}
return eval(namespace);
}
//Then, use this in your class definition libs:
NS('Root.Namespace').Class = function(settings){
//Class constructor code here
}
//some generic method:
Root.Namespace.Class.prototype.Method = function(args){
//Code goes here
//this.MyOtherMethod("foo")); // => "foo"
return true;
}
//Then, in your applications, use this to instantiate an instance of your class:
var anInstanceOfClass = new Root.Namespace.Class(settings);
EDIT: by the way, I wouldn't suggest (for all the security reasons pointed out heretofore) that you base you object names on user input. I can't imagine any good reason you'd want to do that though. Still, thought I'd point it out that it wouldn't be a good idea :)
I'm building one of my first web apps using HTML5, specifically targeting iPhones.
Since I'm pretty new to this, I'm trying to develop some good coding habits, follow best practices, optimize performance, and minimize the load on the resource-constrained iPhone.
One of the things I need to do frequently... I have numerous divs (each of which has a unique id) that I'm frequently updating (e.g., with innerHTML), or modifying (e.g., style attributes with webkit transitions and transforms).
In general - am I better off using getElementByID each time I need a handle to a div, or should I store references to each div I access in "global" variables at the start?
(I use "global" in quotes because I've really just got one truly global variable - it's an object that stores all my "global" variables as properties).
I assume using getElementByID each time must have some overhead, since the function needs to traverse the DOM to find the div. But, I'm not sure how taxing or efficient this function is.
Using global variables to store handles to each element must consume some memory, but I don't know if these references require just a trivial amount of RAM, or more than that.
So - which is better? Or, do both options consume such a trivial amount of resources that I should just worry about which produces more readable, maintainable code?
Many thanks in advance!
"In general - am I better off using getElementByID each time I need a handle to a div, or should I store references to each div"
When you're calling getElementById, you're asking it to perform a task. If you don't expect a different result when calling the same method with the same argument, then it would seem to make sense to cache the result.
"I assume using getElementByID each time must have some overhead, since the function needs to traverse the DOM to find the div. But, I'm not sure how taxing or efficient this function is."
In modern browsers especially, it's very fast, but not as fast as looking up a property on your global object.
"Using global variables to store handles to each element must consume some memory, but I don't know if these references require just a trivial amount of RAM, or more than that."
Trivial. It's just a pointer to an object that already exists. If you remove the element from the DOM with no intention to use it again, then of course you'll want to release your hold on it.
"So - which is better? Or, do both options consume such a trivial amount of resources that I should just worry about which produces more readable, maintainable code?"
Depends entirely on the situation. If you're only fetching it a couple times, then you may not find it worthwhile to add to your global object. The more you need to fetch the same element, the more sense it makes to cache it.
Here's a jsPerf test to compare. Of course size of your DOM as well as length of variable scope traversal and the number/depth of properties in your global object will play some role.
Using a local variable or even an object property is much faster than getElementById(). However, both are so fast that their performance is generally irrelevant compared to any other operation you might do once you have the element. Event setting a single property on the element is orders of magnitude slower than retrieving it by either method.
So the main reason to cache an element is to avoid the rather long-winded document.getElementById(... syntax, or to avoid having element ID strings scattered all over your code.
I have this piece of code that I've written and read that in order for it to work correctly I must use parameters so I did and it works perfectly, however I cant figure out for the life of me what parameters are and how they work. I read through a ton of articles all over the web but I just couldn't figure out how parameters work. How does one parameter know to grab instructions from another. The whole idea is just really frustrating. Also this is kind of a side question. Can I getElementBy Class instead of Id or is there anything similar to get getElementById() for classes? Thanks so much in advance.
Below is the code that is in the script.js file:
function setValue(field)
{
if(''!=field.defaultValue)
{
if(field.value==field.defaultValue)
{
field.value='';
}
else if(''==field.value)
{
field.value=field.defaultValue;
}
}
}
and I called this script to run with the code below:
<textarea id="info"
class="textArea"
name="comment"
cols="40" rows="10"
onfocus="setValue(this)"
onblur="setValue(this)">
Whats Your Name
</textarea>
Parameters
If by "parameter" you mean "argument", it's not at all clear what you mean by "How does one parameter know to grab instructions from another." Arguments/parameters don't grab "instructions" from each other.
Since it's not at all clear what you're actually asking here, I won't go into any kind of detail, but I will warn that function arguments actually work a bit differently in JavaScript than in many other languages like C, C#, or Java.
The traditional model is a special memory area called a "stack": The caller pushes arguments onto the stack, and the callee (the function being called) pulls them off the stack.
JavaScript doesn't use the stack model, though. Instead, when a function is called, an object called an execution context is allocated, and along with it something called a variable object, and the arguments (and a few other things) end up being properties on the variable object. (This happens invisibly behind the scenes, you don't actually get direct references to either object, but the fact of them is clear from edge case behaviors.)
Getting Elements by Class Name
There's getElementsByClassName which is widely-supported except by IE. But if you search for "getElementsByClassName IE" you'll find a variety of implementations for IE that you can drop into your page.
When I hear the word "parameter", I usually think of references that are passed into methods for execution. Is that what you mean? Whether it's a function or an object method, that's usually the name that we give to the object references that are passed in. Is that what you have in mind?
Yes, it's possible to query for a DOM element using div names, as long as you've written your page to do so. jQuery is the library that most people are using to manipulate the DOM in an HTML page. It has lots of methods for querying for different DOM elements. Perhaps that is what you want.
Well, I think many people call them parameters while many others call them arguments, but they are both the same: They are what you pass to a function. What that does with the parameters/arguments is completely dependent on the function. You could pass a DOM element, a string, an object, you name it.. but the function ultimately decides what to do with it.
Your side-question about getElementByClass, there is getElementsbyClassName, but its not cross-browser compatible, meaning it only works in certain browsers. There are libraries that handle all of the cross-browser madness for you though, such as Sizzle.
I find myself needing:
var self = this;
a lot within my javascript 'classes'. Although this is commonly done, it feels a bit wrong.
What I'm hoping to find in this question is a better way to deal with this, or a something to convince me this is quite alright.
Is this the standard way to keep the correct bindings around? Should I standardize on using 'self' everywhere, unless i explicitly need 'this'.
edit: I know exactly why I need this, I'm just wondering if it's considered a bit evil and why. I'm aware there's also the 'apply' built-in javascript function to explicitly define scope when calling a method. Is it better?
As others have said: This "extra variable" is (at some level) the only way to get about the fact that this is a special expression and thus, being not a variable, is not bound in an execution context/closure.
However, what I think you are asking (or what I really want to answer) is:
Should one put var self = this at the top of every method/constructor?
Summary
While I tried this once, and had the same question, I no longer use this approach. Now I reserve the construct for when I need access in a closure. To me it adds a little "hey, this is what I really want!" semantic to my code:
this -> this and self -> this (but really that) in a closure
Questions ala carte:
...Although this is commonly done, it feels a bit wrong. What I'm hoping to find in this question is a better way to deal with this, or a something to convince me this is quite alright.
Do what feels right to you. Don't be afraid to try one method and switch back later (but please try to remain consistent within each project :-)
Is this the standard way to keep the correct bindings around? Should I standardize on using 'self' everywhere, unless i explicitly need 'this'.
"self" is the most common name used. As per above, I prefer the opposite approach -- to use this except when a closure binding is required.
..if it's considered a bit evil and why.
Evil is a silly subjective term (albeit fun sometimes). I've never said it was evil, just why I do not follow the approach. Some people tell me I am "evil" for not using semi-colons. I tell them they should actually come up with good arguments and/or learn JavaScript better :-)
I'm aware there's also the 'apply' built-in javascript function to explicitly define scope when calling a method. Is it better?
The problem with apply/call is that you must use them at point of the function invocation. It won't help if someone else calls one of your methods as the this may already be off. It's most useful for doing things like the jQuery-style callbacks where the this is the element/item of the callback, etc.
As an aside...
I like to avoid "needing self" on members and thus generally promote all member functions to properties where the receiver (this) just "flows through", which is normally "as expected".
The "private" methods in my code begin with a "_" and if the user calls them, that's on them. This also works better (is required, really) when using the prototype approach to object creation. However, Douglas Crockford disagrees with this "private" approach of mine and there are some cases where the look-up chain may thwart you by injecting an unexpected receiver:
Using the "self" bound in the constructor also locks the upper limit of the look-up chain for a method (it is no longer polymorphic upward!) which may or may not be correct. I think it's normally incorrect.
Happy coding.
Yes, this is the standard way.
Function.apply() and Function.call() can help, but not always.
Consider the following
function foo()
{
var self = this;
this.name = 'foo';
setTimeout( function()
{
alert( "Hi from " + self.name );
}, 1000 );
}
new foo();
If you wanted to do this but avoid the usage of a variable like self and use call() or apply() instead... well... you look at it and start to try, but soon realize you just can't. setTimeout() is responsible for the invocation of the lambda, making it impossible for you to leverage these alternate invocation styles. You'd still end up creating some intermediary variable to hold a reference to the object.
Is this the standard way to keep the correct bindings around?
There is no standard, where JavaScript and class/instance systems are concerned. You will have to choose what kind of object model you prefer. Here's another link to a backgrounder; conclusion: there is no conlusion.
Typically keeping a copy var self= this;(*) in a closure goes hand-in-hand with an object model built around closures with per-instance copies of each method. That's a valid way of doing things; a bit less efficient, but also typically a bit less work than the alternative, an object model built around prototyping, using this, apply() and ECMAScript Fifth Edition's bind() to get bound methods.
What could be counted more as ‘evil’ is when you have a mish-mash of both styles in the same code. Unfortunately a lot of common JS code does this (because let's face it, no-one really understands JavaScript's bizarre native object model).
(*: I typically use that instead of self; you can use any variable name you like, but self already has an somewhat obscure and completely pointless meaning as a window member that points to the window itself.)
Just came across this question because my coworkers addicted to self/that variables and I wanted to understand why...
I think there is a better way to deal with this in nowdays:
function () {}.bind(this); // native
_.bind(function () {}, this); // lodash
$.proxy(function () {}, this); // jquery
In javascript and other languages with closures, this can be a very important thing to do. The object that this refers to in a method can actually change. Once you set your self variable equal to this, then self will reliably remain a reference to the object in question, even if this later points to something different.
This is an important difference in javascript compared to many other languages we work in. I'm coming from .Net, so this type of thing seemed strange to me at first too.
Edit:
Ah, okay, you know all that. (maybe still helpful for someone else.) I'll add that Apply (and Call) are more for using from "the outside", giving to a function you're calling a specific scope that you already know about. Once you're inside a function and you're about to cascade further down into closures, the technique:
var self = this;
is the more appropriate way (easy and clear) way to anchor your current scope.
It's 6 years later, and I have some things to add myself:
bind() is now common enough to be used everywhere. I use it often as an alternative. Sometimes it feels clearer. I still on occasion use var self = this;. though.
Arrow functions slowly are becoming viable for usage. The syntax is a bit shorter which is nice, but I think the killer feature really is that by default they always bind to the parent scope.
This:
var self = this;
var foo = function(a) {
return self.b + a;
};
Can now be written as :
var foo = a => this.b + a;
This is the 'most optimistic' usage of arrow functions, but it's pretty sweet.
And just to concluse, there's nothing wrong with:
var self = this;
Most likely this is done as a way to maintain a reference to this when the scope is about to change (in the case of a closure). I don't know that I'd consider it a bad practice or pattern in and of itself, no. You see similar things a lot with libraries like jQuery and a great deal with working with AJAX.
I think there's an argument to be made for always including var self = this in every method: human factors.
It's needed often enough that you wind up having a mishmash of methods accessing this and others using self for the same purpose. If you move code from one to the other, suddenly you get a bunch of errors.
At the same time, I catch myself absent-mindedly writing self.foo out of habit when I haven't needed or added a var self = this. So I think it could make sense to just make a habit of always including it, needed or not.
The only trouble is... this, self, or that are all an ugly pox on your code and I kind of hate them all. So I think it is better to avoid using delegated methods where possible so that you can avoid using this, that or self the vast majority of the time, and use .bind(this) when you might otherwise resort to self/that. It's very rare that using delegates on the prototype is actually going to save you any substantial amount of memory anyway.
A nice side effect of that approach is that you don't have to prefix all your private variables with _, as they will be truly private and the public properties will be called out by the leading this., making your code more readable.
As bobince said, var that = this is better because it doesn't shadow window.self. self = this sounds less awkward to me, but sometimes you get confusing error messages like property myMethod not found on global, because you forgot the self = this line.
I just want to point out that 'self' is equivalent to 'window', try outputting window === self to the console. You should use this pattern with 'that' or something similar as a variable name, avoid using 'self' since it is already in use by the browser (one mistake and you will create yourself a global variable).
Even though it sounds weird, it is better to use 'that' for its name because other developers will immediately know what you were trying to accomplish in your code, avoid using nonstandard variable names.
I believe that this is an important note, but it was only mentioned in one comment, so I wanted to make it more visible.
This was useful at some point in time, using closure to pass scope, but if you're looking for the standard way of developing and handle the scope properly, use :
myFunction.bind(this)
or like some people suggest the arrow function.
On thing to keep in mind : having a variable replace this is not straight forward and can lead to confusion. If it's needed, it's the sign that the code is not structured optimally.
I like it. It is "self"-explanatory. Douglas Crockford has some things to say about this. He states that using "that" is convention. You can see Crockford for free if you scoot over to yui-theater and watch hes videos about Javascript.
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 eval actually isn't evil.
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 your global window object, cookies, DOM etc. 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, using setTimeout like
setTimeout("myfunction();", 2000); // don't do that
This should always be written like
setTimeout(myfunction, 2000);
Letting Javascript parse Javascript, has a big performance impact.
Eval Evil.
Eval is evil as eval'd code cannot be optimised by javascript interpreters and minifiers which could cause quite a lot of issues because of that (perhaps the interpreter or minifier understands it wrong, or due to the conversion stuffs up the eval'd scope). The other side of the coin is that typically 99% of eval'd code could be rewritten to not use eval - it may require a ton of thinking and problem solving but typically that is the case.
How to avoid using it.
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.
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.
You could use an object to store the variables that you are wanting to reference, and then use obj[name]. However without full code this is just a speculation... which should appear to be suitable.