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?
window.execScript
is not crossing browsers, only IE supports it.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With