BarrettNashville BarrettNashville - 6 months ago 13
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:

subtract(7,3)


and it returned
4
. 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

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.

Syntax

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

Parameters

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

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