6

Possible Duplicate:
When is JavaScript’s eval() not evil?

I know, generally using eval() is bad practice.

But for what purpose it is existed there?

What is the correct purpose of eval()?

At what situation it is better to use eval()?

Community
  • 1
  • 1
rajakvk
  • 9,775
  • 17
  • 46
  • 49

5 Answers5

9

eval() provides access to the JavaScript compiler and this ultimately allows for code to be executed at a later time. The arguments passed to the function are passed to the JavaScript compiler after which the code is executed.

Developers argue about the security of eval(). It is less secure, but if you're absolutely sure your input is sanitized before passing it along, then it shouldn't be a problem.

Also, the results of eval() are generally slower because the code has not yet been compiled nor cached. There's obviously going to be a performance hit for using the function.

It's also difficult to debug code that results from the use of eval() because there is little-to-no contextual information (think line numbers) about the code that is ultimately executed.

In terms of web development, one of the current most popular uses of eval() is to deserialize a JSON string usually in the context of Ajax applications; however, this isn't to say that there aren't many other uses.

Tom
  • 15,527
  • 5
  • 48
  • 62
8

eval

Evaluates a string of JavaScript code without reference to a particular object.

If you construct an arithmetic expression as a string, you can use eval to evaluate it at a later time. For example, suppose you have a variable x. You can postpone evaluation of an expression involving x by assigning the string value of the expression, say "3 * x + 2", to a variable, and then calling eval at a later point in your script.

Be careful when using eval

eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension.

Community
  • 1
  • 1
rahul
  • 184,426
  • 49
  • 232
  • 263
  • +1 This answer seems OK to me so I upvoted it. Whoever downvoted should explain why. –  Oct 20 '09 at 11:49
  • Is the downvote for "Don't use eval"? – rahul Oct 20 '09 at 11:50
  • I don't know but there was a strange downvote on the answer. It seems to have gone now. –  Oct 20 '09 at 11:52
  • I didn't downvote it but I think the voter probably didn't like the unnecessary emphasis on not using eval. http://stackoverflow.com/questions/197769/when-is-javascripts-eval-not-evil – Andy E Oct 20 '09 at 11:53
  • 3
    I don't like absolutes like "Don't use eval!". eval is a tool. Use it when you need that specific tool, don't use it any other time. The trick is to learn the proper definition of "need". – Bryan Oakley Oct 20 '09 at 11:55
  • The proper definition is just below the emphasized line. – rahul Oct 20 '09 at 11:55
  • @Bryan: couldn't have put it better myself. – Andy E Oct 20 '09 at 11:56
  • @phoenix: Much better :) – Andy E Oct 20 '09 at 11:57
  • You say *"You can postpone evaluation of an expression involving x by assigning the string value of the expression, say "3 * x + 2", to a variable, and then calling eval at a later point in your script."* I think creating a function to be executed later that multiplies its argument by three and adds two would be preferable to using `eval`. – Tim Down Oct 20 '09 at 12:06
2

You might want to check this article, below is a direct quote from the page which sums up the power of eval.

The JavaScript EVAL command can be very powerful when using dynamic content in Web-based applications. EVAL can reduce code and eases interaction with data that is unknown at load time, but there are drawbacks to take into account.

The real power of this command is its ability to work with data that is not known at load time—for example, user-entered data. As I have mentioned, EVAL takes any string that you provide and executes it returning a result, if one is applicable. You can use this to execute JavaScript where what you are being asked to execute is not known at load time. For example if we have a calculation script that takes an equation provided by the user and returns a result, you can use EVAL to perform the calculation.

Community
  • 1
  • 1
Filip Ekberg
  • 36,033
  • 20
  • 126
  • 183
  • It's `eval`, not `EVAL`. – Tim Down Oct 20 '09 at 12:07
  • 1
    Oh really?! It's a quote. Send your complaints to the author. – Filip Ekberg Oct 21 '09 at 09:34
  • I'm aware it's a quote, but you have chosen to quote it in your answer. I'm sure no-one's really going to be confused by the capitalization in the context of this question but it's an odd way to present the name of a function in a language in which function names are case sensitive. – Tim Down Oct 21 '09 at 22:09
1

I don't think it's so much bad to use it as dangerous. People say don't use eval because it opens loopholes for abuse. It's OK to use it if your input is safe. It is used in Doug Crockford's JSON parser, for example, after the input has been checked using a regular expression to make sure there is no "dangerous" content.

The other reason people tell you not to use it is that if you use eval too much, people will start calling you Eval Knievel.

0

I was experimenting recently with the eval() command while trying to come up with a new convention for a new project.

What I wanted was this: I liked the idea of having private, public, and privileged methods, ala. Doug Crockford's article, but I wanted to be able to expose public methods/variables at the TOP of my classes instead of at the bottom as is usual.

Consider this:

var Singleton = function() {
    // Private
    function _one() {
        // code...
    }

    function _two() {
        // code...
    }

    // Public
    return {
        one: _one,
        two: _two
    };
}();

With three eval()'s (two nested inside of the main one) I was able to have this syntax:

var Singleton = function() {
    // Public
    var $interface = {
        one: $forward,
        two: $forward
    };

    // Private
    function _one() {
        // code...
    }

    function _two() {
        // code...
    }

    // This does the magic
    return eval($init);
}('Singleton');

And against all odds and common-sense it did work. (Note that I also wanted a way to debug my namespaces which is why you can see a string passed to the singleton. $init took care of this too.)

Anyway, I guess the point of typing all this is to say that eval() isn't necessarily the diseased runt of the JavaScript litter that should be avoided at all costs, and can be used in more ways than just on (trusted!) code sent from a server and JSON de-serializing.

(Although in my case it ended up as a mental-workout, as I had since convinced myself not to bother with private-methods/variables after all and just use a strict namespacing convention.)

Oliver Olding
  • 41
  • 1
  • 8
shuckster
  • 5,279
  • 2
  • 23
  • 22