One of the features introduced by ECMAScript 6 is the ability to indicate default values for unspecified parameters in JavaScript, e.g.
function foo(a = 2, b = 3) {
return a * b;
}
console.log(foo()); // 6
console.log(foo(5)); // 15
Now I'm wondering if it's possible to use default parameters also for functions created dynamically with the Function
constructor, like this:
new Function('a = 2', 'b = 3', 'return a * b;');
Firefox 39 seems to already support default parameters (see here), but the line above is rejected as a syntax error.
Now I'm wondering if it's possible to use default parameters also for functions created dynamically with the Function constructor
Yes, according to the spec this is possible. The parameter arguments are concatenated as always and then parsed according to the FormalParameters
production, which includes default values.
Firefox 39 seems to already support default parameters, but the line above is rejected as a syntax error.
Well, that's a bug :-) (probably this one)
You should be able to work around it by using
var fn = Function('return function(a = 2, b = 3) { return a * b; }')();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With