5

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.

2
  • Hmmm, why do you need a string argument instead of just a =2? It would be slightly more difficult to use, isn't it? Commented Jul 15, 2015 at 11:43
  • 1
    This seems to be related to this bug. Commented Jul 15, 2015 at 14:05

3 Answers 3

1

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; }')();
Sign up to request clarification or add additional context in comments.

Comments

0

As new Function is a form of eval anyway you could use the following code for that task:

eval('function bar (a = 2, b = 3) { return a * b; }');

1 Comment

Probably because it's a function declaration, so eval will return undefined. You should use a function expression instead.
0

I do not know if that is supposed to work - some one else will have to tell you - but if it continues to be a problem, why not use eval()?

Something in the lines on this should be legal:

var fct1 = eval("(function foo(a = 2, b = 3) { return a * b; })")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.