JavaScript: Function Constructor

By Xah Lee. Date: . Last updated: .

Function constructor is the function object Function.

〔➤see JavaScript: Function Object and Properties

Function lets you define function from strings.

The syntax is:

new Function(param_name_1, param_name_2, param_name_3, …, body)

The param_name_1, param_name_2, param_name_3, …, body should be type string.

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

// using constructor to define a function

// function with no parameter
var h1 = new Function("return 3;");
console.log(h1());              // 3
// using constructor to define a function

// function with 1 parameter
var h2 = new Function("a", "return a;");
console.log(h2(4));             // 4
// using constructor to define a function

// function with 2 parameters
var 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.

ECMAScript 2015 §Fundamental Objects#sec-function-constructor

Function Topic

  1. JavaScript: Define Function
  2. JavaScript: Function Optional Parameters
  3. JavaScript: Variable/Function Declaration Order, Name Hoisting
  4. JavaScript Variable Scope: Function Level vs Block Level
  5. JavaScript: Function Declaration vs Function Expression
  6. JavaScript: Closure
  7. JavaScript: Functional Programing
  8. JavaScript: f.call f.apply f.bind
  9. JavaScript: Function Constructor
  10. JavaScript: Function Argument Default Value (ES2015)
  11. JavaScript: Function Rest Parameters (ES2015)
  12. JavaScript: Arrow Function (ES2015)
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.