JS: Function Constructor

By Xah Lee. Date: . Last updated: .

The keyword Function (capital F) lets you construct a function from strings.

The advantage of using Function to define a function is that it lets you create function at run-time. Though, this is rarely needed.

new Function (args)

same as Function (args)

Function(param1, param2, etc, body)

Return a function with specified params and body. The arguments should all be strings.

// function with no parameter
const ff = Function("return 3;");
console.assert(ff() === 3);
// function with 1 parameter
const gg = Function("a", "return a;");
console.assert(gg(4) === 4);
// function with 2 parameters
const hh = Function("a", "b", "return a + b;");
console.assert(hh(3, 4) === 7);

JavaScript. Function