It's not.
eval
and new Function
are just about equally dangerous.
To understand the security flaw caused by eval
and new Function
, read Why is using the JavaScript eval function a bad idea?.
The basic issue is that, when evaluating a string provided by someone else, you can't trust that user to always act appropriately. This is called an injection attack. The attacker can trick your page into doing just about anything they want.
Even if you wrote the code to be executed, you still shouldn't use a String
, either. In almost every case, you can use a function expression to pass a Function
instead of a String
. This is very likely to perform faster, as well as being more readable because it looks like code instead of a string. Compare the formatting on the following definitions:
T1 = new Function('a', 'b', 'alert("hi");return a + b');
T2 = function(a, b) { alert("hi");return a + b }
See how the second one has all of the tokens inside the function body highlighted correctly? That's a sign things are going well.
What are you trying to do?
I effectively used AJAX to pass some code for JAVASCRIPT to execute
There's a better way to get the browser to execute some trusted code from a server: a <script src=...>
element. You can add these dynamically. Then you don't have to load a (potentially enormous) String
payload and pass it through the eval
pipeline, and your browser can start doing smart things code caching.
What's the nuance between eval
and new Function
?
In terms of security, eval
and new Function
have the same flaw. The only difference is that code in a new Function
does not form a closure over your local scope, so there is a very puny increase in security by preventing the injected code from accessing your local variables. But that's really not worth much at all.