Reputation: 5198
Babel is transpiling my ES2015 default arguments to ES5, but it seems to be doing it very verbosely. Here's the original function:
function initStyles(skipScaling = false) {/*...*/}
And here is the result after transpiling:
function initStyles() {
var skipScaling = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
}
If I were to (perhaps naively) implement this, I would do something like this:
function initStyles(skipScaling) {
if (skipScaling === undefined) skipScaling = false;
}
What's the reason Babel handles it this way?
Upvotes: 4
Views: 433
Reputation: 151126
To add some illustration to what @Bergi mentioned it is related to "the number of arguments expected by the function" Function.prototype.length
.
(It was arity
in the past but now obsolete).
In an ES6 environment,
function foo(s = 123) {
console.log(arguments, s)
}
console.log("foo.length", foo.length);
would print out 0
at the end.
The way Babel or Traceur translate it:
function foo() {
var s = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 123;
console.log(arguments, s);
}
console.log("foo.length", foo.length);
it would also print out 0
at the end.
If written this way:
function bar(s) {
if (s === undefined) s = 123;
console.log(arguments, s);
}
console.log("bar.length", bar.length);
Then it'd print out 1
at the end so it is not entirely the same as ES6.
Upvotes: -1
Reputation: 664969
Parameters that have a default initialiser are not counted for the function arity. The .length
of your initStyles
function should be 0
, and Babel replicates that by using the arguments
object to initialise a var
instead of using a named parameter.
Upvotes: 7