6

Practically every javascript guide on the web shouts to me that eval is bad, don't use it, it's a security hole and whatnot. Recently I discovered window.execScript, which seems to do the same thing as eval. Is one better than the other in terms of security or speed?

1

3 Answers 3

8

window.execScript is not crossing browsers, only IE supports it.

3
6

eval is bad but it can be replaced with new Function most of time, it's safer and it's crossbrowser:

var foo = new Function('return 1 + 2');
var baz = eval('function(){ return 1 + 2 }');

The main difference is scope access. eval can affect local variables where new Function creates another scope.

3
  • 3
    should be var foo = new Function('return 1 + 2')(); you missed () in the end
    – Justin
    Aug 12, 2015 at 19:29
  • 1
    Running the baz line from Chrome's debug console gives me a "Uncaught SyntaxError: Unexpected token ("
    – hcvst
    May 8, 2016 at 7:54
  • 1
    You code for baz doesn't work. You need to wrap that function(){...} in () to make it a valid function expression or it won't run: const baz = eval('(function(){return 1 + 2;})'); Apr 19, 2017 at 23:17
1

Update 2019.

Eval is not bad, eval is misunderstood, and is really powerful. Pretty much is what power our developers tools. the Function constructor serves the same purpose of eval and even has the same security vulnerabilities

The Function constructor creates a new Function object. Calling the constructor directly can create functions dynamically, but suffers from security and similar (but far less significant) performance issues to eval. However, unlike eval, the Function constructor creates functions which execute in the global scope only. Blockquote https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function

There are legit cases for eval and Function which only real difference is how the scope is handle.

I suggest reading these two posts to increase understanding about this topic https://blogs.msdn.microsoft.com/ericlippert/2003/11/01/eval-is-evil-part-one/ https://javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval/

Bonus: if you want to have new Function or Function to behave the same you can simply do use of indirect eval by typing (0, eval) http://perfectionkills.com/global-eval-what-are-the-options/

So there you go, eval and Function pretty much are the same.

Ps. execScript has been deprecated.

Update 2021

If you are researching eval and you are intending to do a sandbox, make yourself a favor and use something like https://codesandbox.io/post/sandpack-announcement sandpack which has solved most of the problem when implementing a sandbox for javascript.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.