iuliu.net iuliu.net -4 years ago 92
Javascript Question

Why is Babel using the `arguments` object for optional parameters?

I've noticed a somewhat odd transpilation decision from babel, with regards to optional parameters. The following ES6 code:

function myFunction(x = 2, y = 3) {}

gets transpiled to

function myFunction() {
var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 2;
var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 3;

I soon have to hold a presentation about how much shorter and more concise the ES6 syntax is and how it would look in ES5 (via Babel usually). But for me this seems kinda forced and also much less performant. Are there reasons not to do this?:

function myFunction(x, y) {
x = x === undefined ? 2 : x;
y = y === undefined ? 3 : y;

Answer Source

Are there reasons not to do this?

It would conflict with the specification, which says that the arity (.length) of the function is the number of declared parameters prior to the first parameter with a default value or the rest parameter. (This definition starts here; following it through is...fun. But that's what it comes down to.)

Your myFunction has no declared parameters prior to the first one with a default value, and thus has length == 0. If it were transpiled as you suggest, it would have length == 2 instead, which would be a spec violation.

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