Tyrael Archangel
Tyrael Archangel

Reputation: 487

Alternative to eval to execute functions

if i have this code:

var x = "alert('eval is evil')";

Can i execute this without eval?

I searched other posts and found nothing for this situation.

Upvotes: 1

Views: 1614

Answers (5)

jacktheripper
jacktheripper

Reputation: 14249

This is exactly what eval was designed to do. The point is, you should never write code that necessitates the use of eval; 99.99% of the time you're doing it wrong and there are alternatives.

Upvotes: 0

georg
georg

Reputation: 215029

eval is basically an embedded JS interpreter, if you're not happy with the build-in interpreter, you can program your own. It can be complicated or easy, depending on which subset of the language you're going to support. For the given code example, that's fairly easy:

re=/(\w+)\('(.+?)'\)/
code="alert('eval is evil')"
m=code.match(re)
window[m[1]](m[2]) // works

For serious work, consider using a parser generator, like jison or peg.js.

Upvotes: 0

iConnor
iConnor

Reputation: 20209

There is no other function in javascript you can use to execute random javascript code instead of eval, however the only other option is to append it to the page via <script> like so

var x = "alert('eval is evil')",
    script = document.createElement('script');
script.textContent = x;
script.type = 'text/javascript';
document.head.appendChild(script);

Upvotes: 1

Stefan
Stefan

Reputation: 4160

you can add it to the Function constructor and then call that

var x = new Function("alert('this is not much better')");
x();

however, that is not much better. Evaluating javascript either way is prone to errors and in some cases insecure and generally, if you need eval in your code your app design is wrong

Upvotes: 1

Ted Hopp
Ted Hopp

Reputation: 234857

If you insist on setting x to a string, there's no simple way to avoid eval.* However, you can do this instead:

var x = function() { alert('eval is evil'); };

Or, in modern JS engines:

var x = alert.bind(null, 'eval is evil');

Then you can simply execute x:

x();

*There are techniques to avoiding eval. For instance, you can add a script tag to the document containing the text that you want executed.

Upvotes: 0

Related Questions