BarrettNashville BarrettNashville - 2 years ago 65
Javascript Question

Why/How does this work: var subtract = Function('a', 'b', 'return a - b');?

I was reading through the Airbnb JavaScript Style Guide and I came across this section that mentions the following function:

var subtract = Function('a', 'b', 'return a - b');

I tested this in the Chrome debugger console by entering the line above and then entering:


and it returned
. I was very surprised that it actually worked.

The style guide mentioned that it is not a good idea to do this, but it got me to thinking about this function syntax. I've never seen a function that has no body return a proper result.

How/why does this work, how long has it been around, and what are the guidelines/best practices for using it?

Answer Source

This creates a function using the Function object instead of the "normal" function syntax. Notice the capital "F".

var subtract = Function('a', 'b', 'return a - b');

Means that you define a function with parameters a and b, with body return a - b. It's equivalent to

var subtract = function (a, b) { return a - b; };

Typically, you want to use new when invoking a constructor like this, but it works just as well without it; it's just a little harder to read (for humans).

From the Mozilla Developer Network explanation:

The Function constructor creates a new Function object. In JavaScript every function is actually a Function object.


new Function ([arg1[, arg2[, ...argN]],] functionBody)


arg1, arg2, ... argN
Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript identifier or a list of such strings separated with a comma; for example "x", "theValue", or "a,b".

A string containing the JavaScript statements comprising the function definition.


Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download