2

I came across a code that look like this:

 const tempFunc = exp => {
  return new Function(`return ${exp}`)()
 }

first question: is it self invoking the function and return it?. what does tempFunc return exactly?

second question: if we call the function:

let result=tempFunc('3+2')

the result is 5.how does it convert the string and calculate the result?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
KeyvanKh
  • 311
  • 1
  • 6
  • 2
    That is very much the same as `eval`, but evaluates a single expression (because of the `return`). WARNING: this single-expression thing can be bypassed, don't use with insecure input! – FZs Dec 31 '20 at 16:04
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Function – Bergi Dec 31 '20 at 16:16
  • No self-invocation here. – Bergi Dec 31 '20 at 16:17

2 Answers2

2

When you call tempFunc('3+2') it returns new Function("return 3+2")(), which will create a function (function() { return 3+2 };) and then call that function.

Conversely, if tempFunc looked like this:

const tempFunc = exp => {
  return new Function(`return ${exp}`);
 }

Then it would just return the new function uncalled and you'd have to call it separately: tempFunc('3+2')();

Function Constructor

The function constructor (new Function()) is pretty interesting; you can basically tell it what arguments to expect as the first n arguments and the final argument is the function body. In your example, there are no arguments to our new function, but we could create one that takes arguments:

const tempFunc = num => {
  return new Function('x', `return x + ${num}`)(2);
}

tempFunc(3);
// 5
Nick
  • 16,066
  • 3
  • 16
  • 32
0

In case the arrow functions are confusing for you, you can also write it similar like this:

 const tempFunc = function(exp) {
  const compiledFunc = new Function(`return ${exp}`)
  return compiledFunc()
 }

This:

new Function(`return ${exp}`)

creates a new Function object with the submitted string. The string ("3+2" in your example) is compiled as a function as if it was javascript code. This Function object can then be called as if it was a normal javascript Function. Thats what the two paranthesis do at the end of the line:

return new Function(`return ${exp}`)() // <-- these call it

So if you call that tempFunc it runs the string as javascript code and returns it, quite similar to what eval does.

likle
  • 1,717
  • 8
  • 10