JS: Function Constructor

By Xah Lee. Date: . Last updated: .

Function constructor is the function object Function.

[see JS: Function Object]

Function lets you define function from strings.


  1. new Function (…) → equivalent to Function (…)
  2. Function(param_name_1, param_name_2, param_name_3, …, body)

The param_name_1, param_name_2, param_name_3, …, body should be strings.

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
const h1 = new Function ("return 3;");
console.log ( h1() );              // 3
// using constructor to define a function

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

// 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.


ECMAScript 2015 §Fundamental Objects#sec-function-constructor

Function Topic

  1. JS: Define Function
  2. JS: Functional Programing
  3. JS: Arrow Function
  4. JS: Function Parameters
  5. JS: f Declaration vs Expression
  6. JS: Closure
  7. JS: Function Call, Apply, Bind
  8. JS: Function Argument Default Value
  9. JS: Function Rest Parameters
  10. JS: Function Argument Destructure
  11. JS: Function Object
  12. JS: Function.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.