iuliu.net
iuliu.net

Reputation: 7145

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;
}

Upvotes: 2

Views: 384

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074989

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.

Upvotes: 4

Related Questions