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:
If
new Function('return (a = 22);')()were used, the local variableawould retain its value. Nevertheless, some JavaScript programmers such as Douglas Crockford believe that neither should be used unless absolutely necessary, and evaling/using theFunctionconstructor on untrusted data is insecure and unwise.