There is another way of creating a function. It’s not used often, but in times, there is no alternative.
Here is the syntax that can be used for function-creating:
let fn = new Function([arg1, arg2, ...argN], functionBody);
It is created with the following arguments: arg1...argN and the functionBody.
It is demonstrated in the following example:
In another example, you can see a function without arguments but with the function body:
The most significant difference from other ways of creating a function is that it is created from a string passed at run time. In all the previous ways, developers were required to write the function code inside the script. But, with the help of the new Function, you can turn any string into a function. For instance, you can get a new Function from the server and execute it, like this:
let str = ...receive the code from a server dynamically... let func = new Function(str); func();
Particular cases require to use it. For example, when you get a code from a server or compile a function from a template.
As a rule, a function remembers where it was created in the particular property [[Environment]]. Hence, it references the Lexical Environment from where it’s made. Previously it was represented in the chapter Variable Scope.
When you create a function by applying new Function, the [[Environment]] references not the current Lexical Environment, but also the global one.
A function like this has no access to external variables:
Comparing it with normal behavior turns out:
The new Function may seem a little strange, but in practice, it can be beneficial.
Let’s imagine that you intend to make a function from a string. At the time of writing the script, that function code is not known. But it can be found out during the execution. It might be received either from the server or from another source. An interaction between the new function and the main script is a necessity.
For example, when a function has let userName, the minifier may shorten it by replacing it with let a or another shorter variant.
Note that if new Function had access to the external variables, it might not be able to find the renamed userName. In case the new Function had access to the external variables, there would be no problems with minifiers.
For passing something to a function, created as new Function, its arguments should be used.