Increased Capabilities of the Function Constructor
The Function
constructor is an infrequently used part of JavaScript that allows you to dynamically create a new function. The arguments to the constructor are the parameters for the function and the function body, all as strings. Here’s an example:
var add = new Function("first", "second", "return first + second");
console.log(add(1, 1)); // 2
ECMAScript 6 augments the capabilities of the Function
constructor to allow default parameters and rest parameters. You need only add an equals sign and a value to the parameter names, as follows:
var add = new Function("first", "second = first",
"return first + second");
console.log(add(1, 1)); // 2
console.log(add(1)); // 2
In this example, the parameter second
is assigned the value of first
when only one parameter is passed. The syntax is the same as for function declarations that don’t use Function
.
For rest parameters, just add the ...
before the last parameter, like this:
var pickFirst = new Function("...args", "return args[0]");
console.log(pickFirst(1, 2)); // 1
This code creates a function that uses only a single rest parameter and returns the first argument that was passed in.
The addition of default and rest parameters ensures that Function
has all of the same capabilities as the declarative form of creating functions.