JavaScript: Function Constructor
Function
lets you define function from strings.
Function(param_name_1, param_name_2, param_name_3 etc, body)
- Return a function with specified params and body. The arguments should all be strings.
new Function (âŠ)
-
same as
Function (âŠ)
The advantage of using Function()
to define a function is that it lets you create function at run-time. Though, this is rarely needed.
Example:
const f = Function("a", "b", "return a + b;");
// function with no parameter const h1 = new Function ("return 3;"); console.log( h1() ); // 3
// function with 1 parameter const h2 = new Function("a", "return a;"); console.log(h2(4)); // 4
// function with 2 parameters const h3 = new Function("a", "b", "return a + b;"); console.log(h3(3,4)); // 7
Using new Function()
is similar to the use of eval(âŠ)
, and you should be careful to not eval user generated input. Otherwise, it's a security risk.