javascriptfunctionevalcalculationecmascript-2016

Why does 'new Function' not work as eval?


I have for example code (with 'new Function') which will open an alert window:

   new Function`alert(1)`; // Works OK

The same code on eval

   eval('alert(1)'); // Works OK

But why if I use calculating:

 new Function`2+2`; // It does not work. It shows {}

Eval works correctly:

   eval('2+2'); // Works OK , will be 4

Why is the code

 new Function`2+2`;

not working?


Solution

  • I think it's impossible to use a function call with a template string for calculating. It works only with single quotes or double quotes.

    const result = new Function('return 2+2')();
    
    console.log(result); // 4