1

I have never encountered a situation where I needed eval().

Often times, people say that the [] property accessor makes eval() redundant.

Actually, isn't the execution of a pain statement exactly the same thing as pushing it as an argument into the eval() function. What is it actually used for?

Can you provide examples of when it might be useful to use eval()?

Mohsen
  • 64,437
  • 34
  • 159
  • 186
ppecher
  • 1,978
  • 4
  • 19
  • 30
  • 1
    Does this answer your question? [When is JavaScript's eval() not evil?](https://stackoverflow.com/questions/197769/when-is-javascripts-eval-not-evil) – Oliver Sieweke May 17 '21 at 16:26

5 Answers5

2

eval is something of a hybrid between an expression evaluator and a statement executor. It returns the result of the last expression evaluated (all statements are expressions in Javascript), and allows the final semicolon to be left off.

Example as an expression evaluator:

foo = 2;
alert(eval('foo + 2'));

Example as a statement executor:

foo = 2;
eval('foo = foo + 2;alert(foo);');

One use of JavaScript's eval is to parse JSON text, perhaps as part of an Ajax framework. However, modern browsers provide JSON.parse as a more secure alternative for this task.

source

With that in mind the only real reason I can see you wanting to use eval() is for executing user input.. but that leads to serious security risks... so in short I would say eval() (in javascript at least) has become a mute function; replaced by the many specific functions that would have invoked you to use eval() in the past.

Another idea. You could possibly use it to execute pure js being returned by ajax

your server could pass back a string containing "alert('hello world');" and you could eval(returnData);.

rlemon
  • 17,518
  • 14
  • 92
  • 123
2

Take your favourite Javascript library and grep for uses of eval. Hopefully your library is made by knowleadgeable people and the only cases of eval are the kind of good example you are looking for.

I looked in the Dojo Toolkit and one of the evals there is in the module loader (it apparently has a mode that does an AJAX request for the missing module and evals to execute the code instead of creating a script tag).

hugomg
  • 68,213
  • 24
  • 160
  • 246
1

The most common situation where I find the need to use eval is when I get a json string that I want to use as an object.

var obj = eval('('+jsonString+')');
MacAnthony
  • 4,471
  • 2
  • 23
  • 26
  • 2
    Why not use `JSON.parse` for that? – rlemon Sep 30 '11 at 21:52
  • There was a time before JSON.parse ... But nowadays no reason for eval. – hugomg Sep 30 '11 at 21:54
  • hehe, i do mention all of this in my answer. :P – rlemon Sep 30 '11 at 22:00
  • I don't believe json.parse is supported by IE7 or earlier. That is still a fair amount of browser traffic. – MacAnthony Sep 30 '11 at 22:02
  • @macanthony then you can use jQuery.parseJSON: http://api.jquery.com/jQuery.parseJSON/ – Icarus Sep 30 '11 at 22:21
  • You can't always use external libraries. It still has it's place. – MacAnthony Sep 30 '11 at 22:24
  • How is concatenating a JSON string with parenthesis converting it to an object? Isn't JSON an object already (just with stricter identifer names)? thx for your answer. – ppecher Sep 30 '11 at 22:33
  • 1
    The parens are only a precaution separating it from other object/variables/functions that might be in the code that's there to avoid confusion. JSON is a string representing a javascript object. If you wrote the code in the string in javascript, it would just make the object. That's what eval does. Runs the string as if it were javascript. – MacAnthony Sep 30 '11 at 22:41
  • @MacAnthony, the parens are actually to force the evaluation of the JSON string in *expression context*, for example, if you `eval` a string that represent a simple object, let's say: `'{"foo":1}'`, the first curly brace would be parsed as the star of a Block, then we would get a `SyntaxError` since the `"foo"` literal is not a valid identifier for a *labelled statement*. See also: http://stackoverflow.com/q/3360356 and http://stackoverflow.com/q/3731802 – Christian C. Salvadó Oct 01 '11 at 00:59
0

I don't know how terrible or otherwise this is, but I used it to run scripts inside dynamically loaded HTML templates, as those aren't automatically run.

evaluateScripts = function(container) {
    var scripts, i;
    scripts = container.querySelectorAll("script[type='application/javascript']");
    for (i = 0; i < scripts.length; i++) {
        eval(scripts[i].innerHTML);
    }
}
Joel Roberts
  • 149
  • 1
  • 9
0

I don't know about legitimate, but this is how jquery uses eval-

globalEval: function( data ) {
    if ( data && rnotwhite.test( data ) ) {
        // We use execScript on Internet Explorer
        // We use an anonymous function so that context is window
        // rather than jQuery in Firefox
        ( window.execScript || function( data ) {
            window[ "eval" ].call( window, data );
        } )( data );
    }
},
kennebec
  • 102,654
  • 32
  • 106
  • 127