Function constructor in JavaScript

As you know that we create or define function in JavaScript using function keyword. So you can create a simple Add function in JavaScript as given in below,

 var add = function Add(a, b) {
                return a + b;

The other way to create functions in JavaScript is using Function constructor. Function constructor creates and complies a JavaScript function at run time.

  var add = new Function
                "return a+ b; "

You can create a function using Function constructor as below,

  • Parameters are passed as string in Function constructor
  • Last parameter is always body of the function
  • Body of the function is also in string
  • Statements in body are separated with semicolon
  • If there is no input parameter then body of function would be first and only parameter in constructor
  • Any number of arguments can be passed in Function constructor

A function created using JavaScript constructor with no input parameter is as follows,

function GetData() {

          var add = new Function("alert('hello');")

Two very important points about Function constructor are as follows,

  1. It creates and complies a JavaScript function dynamically at run time
  2. Each time it creates a new object. So creating function using constructor in a loop is not recommended and it is inefficient

Scoping in Function constructor is very important. It always complies as top level function. It never complies as local function so it does not take lexical scoping.

var message = "Hello All";
            function Data() {

                var  message = "Hello Data";
                return new Function("return message");

            var result = Data()();

In above code snippet, as you see message variable is defined at two levels global and local to function. From Function constructor message (variable) is returned. It will take global variable instead of local message variable. You will get output as following


These are the points you need to keep in mind working with Function constructor. I hope you find this post useful. Thanks for reading.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s