Are eval() and new Function() the same thing?


Are these two functions doing the same thing behind the scenes? (in single statement functions)

var evaluate = function(string) {
    return eval('(' + string + ')');
}

var func = function(string) {
    return (new Function( 'return (' + string + ')' )());
}

console.log(evaluate('2 + 1'));
console.log(func('2 + 1'));

No, they are not the same.

  • eval() evaluates a string as a JavaScript expression within the current execution scope and can access local variables.
  • new Function() parses the JavaScript code stored in a string into a function object, which can then be called. It cannot access local variables because the code runs in a separate scope.

Consider this code:

function test1() {
    var a = 11;
    eval('(a = 22)');
    alert(a);            // alerts 22
}

If new Function('return (a = 22);')() were used, the local variable a would retain its value. Nevertheless, some JavaScript programmers such as Douglas Crockford believe that neither should be used unless absolutely necessary, and evaling/using the Function constructor on untrusted data is insecure and unwise.


No.

In your update, the calls to evaluate and func produce the same result. But, they are most definitely not "doing the same thing behind the scenes". The func function creates a new function, but then immediately executes it, whereas the evaluate function simply executes the code on the spot.

From the original question:

var evaluate = function(string) {
    return eval(string);
}
var func = function(string) {
    return (new Function( 'return (' + string + ')' )());
}

These will give you very different results:

evaluate('0) + (4');
func('0) + (4');

new Function creates a function that can be reused. eval just executes the given string and returns the result of the last statement. Your question is misguided as you attempted to create a wrapper function that uses Function to emulate an eval.

Is it true that they share some code behind the curtains? Yes, very likely. Exactly the same code? No, certainly.

For fun, here's my own imperfect implementation using eval to create a function. Hope it sheds some light into the difference!

function makeFunction() {
  var params = [];
  for (var i = 0; i < arguments.length -  1; i++) {
    params.push(arguments[i]);
  }
  var code = arguments[arguments.length -  1];


 // Creates the anonymous function to be returned
 // The following line doesn't work in IE
 // return eval('(function (' + params.join(',')+ '){' + code + '})');
 // This does though
 return eval('[function (' + params.join(',')+ '){' + code + '}][0]');
}

The biggest difference between this and new Function is that Function is not lexically scoped. So it wouldn't have access to closure variables and mine would.


If you mean, will it yield the same results, then yes... but just to eval (aka, "evaluate this string of JavaScript") would be much simpler.

EDIT Below:

It's like saying... are these two math problems the same:

1 + 1

1 + 1 + 1 - 1 + 1 - 1 * 1 / 1


Just want to point out some syntax used in the examples here and what it means:

 var func = function(string) {
     return (new Function( 'return (' + string + ')' )());
 }

notice that the Function(...)() has the "()" at the end. This syntax will cause func to execute the new function and return the string not a function that returns string, but if you use the following:

 var func = function(string) {
     return (new Function( 'return (' + string + ')' ));
 }

Now func will return a function that returns a string.


In that example, the results are the same, yes. Both execute the expression you pass. This is what makes them so dangerous.

But they do different things behind the scense. The one involving new Function(), behind-the-scenes, creates an anonymous function from the code you supply, which is executed when the function is invoked.

The JavaScript you pass to it is technically not executed until you invoke the anonymous function. This is in contrast to eval() which executes the code right away, and doesn't generate a function based on it.