Eval is Evil, Part One


The eval method
-- which takes a string containing JScript code, compiles it and runs it -- is probably
the most powerful and most misused method in JScript. There are a few scenarios in
eval is
invaluable.  For example, when you are
building up complex mathematical expressions based on user input, or when you are
serializing object state to a string so that it can be stored or transmitted, and
reconstituted later.


these worthy scenarios make up a tiny percentage of the actual usage of
eval.  In
the majority of cases,
eval is
used like a sledgehammer swatting a fly -- it gets the job done, but with too much
power.  It's slow, it's unwieldy, and
tends to magnify the damage when you make a mistake.  Please
spread the word far and wide: if you are considering
eval then
there is probably a better way.
hard before you use


me give you an example of a typical usage. 






setspan(num, text)


+ num + ".innerText = '" + text + "'");




the program is getting its hands on a number, and it wants to map that to a particular
span.  What's wrong with this picture?


pretty much everything.  This
is a horrid way to implement these simple semantics.
off, what if the text contains an apostrophe?  Then
we'll generate


= 'it ain't what you do, it's the way thacha do it';

isn't legal JScript.  Similarly, what
if it contains stuff interpretable as escape sequences?  OK,
let's fix that up.


+ num).innerText = text;

you have to use
eval, eval as
little of the expression as possible, and only do it once.  
seen code like this in real live web sites:


if (eval(foo)
!= null && eval(foo).blah == 123)

= "hello";


Yikes!  That
calls the compiler three times to compile up the same code!  People,
eval starts
a compiler
.  Before
you use it, ask yourself whether there is a better way to solve this problem than
starting up a compiler! 


our modified solution is much better but still awful.  What
num is
out of range?  What if it isn't even a
number?  We could put in checks, but why
bother?  We need to take a step back here
and ask what problem we are trying to solve. 


have a number.  We would like to map that
number onto an object.  How would you
solve this problem if you didn't have
eval?  This
is not a difficult programming problem!  Obviously
an array is a far better solution:


var spans
= new Array(null, myspan1, myspan2, myspan3);

setspan(num, text)


(spans[num] != null)

= text;



since JScript has string-indexed associative arrays, this generalizes to far more
than just numeric scenarios.  Build
any map you want.  JScript even provides
a convenient syntax for maps!


var spans
= { 1 : mySpan1, 2 : mySpan2, 12 : mySpan12 };


compare these two solutions on a number of axes:


what is easier to debug, a program that dynamically generates new code at runtime,
or a program with a static body of code?  What
is easier to debug, a program that uses arrays as arrays, or a program that every
time it needs to map a number to an object it compiles up a small new program?


What's easier to maintain, a table or a program that dynamically spits new code?


which do you think is faster, a program that dereferences an array, or a program that
starts a compiler?


which uses more memory, a program that dereferences an array, or a program that starts
a compiler and compiles a new chunk of code every time you need to access an array?


is absolutely no reason to use
eval to
solve problems like mapping strings or numbers onto objects.  Doing
so dramatically lowers the quality of the code on pretty much every imaginable axis. 


gets even worse when you use
eval on
the server, but that's another post.



Comments (29)
  1. Dan Shappir says:

    If I were to rewrite the HTML I would implement it as:

    function setspan(num, text)
    var span = document.all("myspan" + num);
    if (span != null)
    span.innertext = text;

    No eval and also no lookup table that must be kept in sync with the HTML.

    BTW, we do use eval a couple of time in the BeyondJS library, but BeyondJS is not you average JavaScript code. One example where we use it is to construct functions on the fly. The reason we use eval instead of "new Function" is because we need to create the function in the current scope.

    Speaking of "new Function", eval’s sibling so to speak, here is an interesting if somewhat extreme example of its use:

    I was a lead developer for an application that was a mixed thin/fat client – some of the data was maintained locally, thus accessible while offline. The rest of the data was online. The way we did it was that the entire UI was DHTML + JavaScript, with some frames generated locally and the others provided by a web server.

    The local frames were generated using a custom OSP, feeding data directly into the HTML via binding. The user could filter this view by filling in a search form. The way filtering was done was that the OSP would generate an event, intercepted by a JavaScript event handler. If this handler returned false, the specific record was excluded.

    A big problem was performance – the view could contain hundreds, even thousands of records in extreme cases. Thus, it was imperative that the filtering would be as quick as possible. What I did was generate the JavaScript event handler on the fly based on the user’s input. This way I could construct optimal code for evaluating the specific filter expression.

    Fun times.

  2. Bradley says:

    Another good way to get an element in the DOM is to use:
    document.getElementById("myspan" + num);

    Another benefit of this method (over eval or document.all) is that if you accidentally insert two (or more) elements with the same ID into the document, getElementById will always return an element (the first one), while eval (or document.all) will return a collection of all the elements with that ID, possibly causing code that expects a single element to fail.

  3. Dan Shappir says:

    getElementById has one significant advantage over document.all – it’s part of the DOM standard endorsed by the W3C, and is thus also supported by Mozilla. On the downside, it not supported by IE4 (not sure if anyone still cares about that version).

    I’m not sure, however, that the fact that it returns the first element in the event of multiple existing elements with the same ID is an advantage. It means that if you accidentally create two elements with the same ID you might not notice and as result not fix the bug.

  4. Meme Washer says:

    In the comp.lang.javascript Javascript Best Practices document; I came across an interesting discussion of the reasons for preferring square bracket notation to eval(). The consensus seems to be that eval is evil, and that &quot;if it exists in your page,..

  5. Steve says:

    Eval is easy… Hahahahahahah.

    If  a fly is bugging me and I have a sledgehammer beside me, why go inside for and search for a flyswatter? That might take me half an hour.


    Debugability.   Well if bugs turn up I can always rewrite it the hard way. Also in many cases the eval code may be simpler and more readable.

    Maintainability. Depends on the situtaion. Eval may be better.

    Speed. If it’s fast enough who cares.

    Memory. Aint a problem.

    I think a lot of of "Gurus" are opposed to anything that makes life easier for us lesser beings.

  6. Alberto says:

    Steve Rocks!

    I agree, a religious conception of programming is the whorthest evil there is (bracket should be opened on a new line, etc);

    Though, going back to the eval thing, it is true that the eval is bad and that there is a number of workarounds (one of the reasons why i love js!).

    Workaround A: gotta call a method of an object but i know only the name.

    doing eval(‘obj.’ + methodName) seems a piece of cake. What about obj[methodName]() ? Much better.

    Though there is nothing like:

    function ClassFactory(constructorClassName){

        var myObj;

        eval(‘myObj=new ‘ + constructorClassName +'()’)

        return myObj;


    A class factory on the fly!!!

  7. Twey says:

    — QUOTE —

    Though there is nothing like:

    function ClassFactory(constructorClassName){

        var myObj;

        eval(‘myObj=new ‘ + constructorClassName +'()’)

        return myObj;


    — END QUOTE —

    How about:

    — CODE —

    function ClassFactory(constructorClassName) {

     return new this[constructorClassName]();


    — END CODE —

    (Although the usefulness of this function is debatable, and the names misleading: there are no classes in JScript.)

    Almost* everything that can be done with eval() can be done with square bracket notation, and not only is it more efficient, it’s also almost invariably simpler (you don’t have to worry about whether the input will form a valid JS expression, for a start) and produces neater code than eval():

    — CODE —

    try {

     eval(‘myobject.’ + propName + ‘ = ‘ "’ + propValue + ‘"’);

    } catch(e) {}

    // versus

    myobject.someProperty[propName] = propValue;

    — END CODE —

    Especially note, if we’re discussing getElementById() support, that some older browsers don’t support try/catch, so the only option when given a bad property name or value is to error out if you want to support these browsers.

    * I say "almost" — the example scenarios EricLippert gave are perfectly valid reasons to use eval(), and to write a dedicated JS parser for these situations is (usually) silly when eval() is already available.

    P.S. Ugh, I had to switch browsers to post this — no Konq support on a blog that deals with web coding?

  8. This post is part of a series called JavaScript Demystified . I&#39;m pretty sure by now you have heard

  9. mr.tang says:

    oh,I can't understand.my english is pool enough

Comments are closed.

Skip to main content