Given an arbitrary eval()
, is there a way to convert it to use new Function()
, without breaking compatibility with any input (except for the change in scope)?
The only issue I can think of is that eval allows multiple statements, and returns the result of the last one, without having to add an explicit return
. I cannot think of a way to emulate this with new Function()
:
let code = '4; 5'
> eval(code);
5
> new Function(code)();
undefined
> new Function('return ' + code)();
4
> new Function('return (' + code + ')')();
SyntaxError: Unexpected token ;
Is there something I am missing or is eval()
incompatible with new Function()
in this case?
No, this is indeed impossible with Function()
. The eval
function is the only JavaScript feature that takes statement results into account.