Would like more detail about alternatives to eval() #106

hpuit opened this Issue Oct 27, 2011 · 3 comments


None yet

3 participants

hpuit commented Oct 27, 2011

I understand that I shouldn't use eval(), but I could use more documentation about alternatives.

I would appreciate having examples of common scenarios, with each scenario having a "Good" and "Bad" example. The "Bad" example would use eval() and the "Good" example would achieve the same result without using eval().

Thank you!


The only general alternative I know is:

function uneval(codeString) {
  var blackList = 'window, document';
  return (new Function(blackList, 'return ' + codeString).apply({}, []));

This can be used to evaluate JSON (actual parser is right solution, but just for example):

uneval('{"a" : 1, "b" : 2}'); // -> {a : 1, b : 2}

Problem here is that you have to list all objects you want to "hide" in the black list. For example:

// this is safe:
uneval('window'); // -> undefined
uneval('document'); // -> undefined


// this is not safe:
uneval('alert("I can haz a code injection!")');

Black list is a bad practice in general, because there might be infinite set of things which you have to protect (all global objects and functions).

There is no "right solution" for such general case, I think. We might just list some common cases, like:

  • passing actions as arguments -> use function vars
  • parsing JSON/XML/whatever -> use actual parser
  • allowing users to write scripts -> use interpreter
  • impressing girls -> buy a car
  • etc
hpuit commented May 14, 2012

This is a great start. Thanks!


Good ideas. If anyone would like to contribute the above list as a pull request I'd be happy to merge!

@timruffles timruffles closed this Apr 30, 2014
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment