Reputation: 7891
While reading about new ES6 features, I found the great way to define default values:
In ECMAScript 6 we can add default values to the parameters of a function. This means that if we don’t pass in arguments later in the function call, the default parameters will be used. In ES5 the default values of parameters are always set to undefined, so the new possibility to set them to whatever we want is definitely a great enhancement of the language.
So it's very simple to use it like this:
function f(p1=1, p2=2, p3=3, p4=4, p5=5){
return "{p1: " + p1 + ", p2: " + p2 + ", p3: " + p3 + ", p4: " + p4 + ", p5: " + p5 + "}";
}
var test = f();
console.log( test );
//outputs: {p1: 1, p2: 2, p3: 3, p4: 4, p5: 5}
I'm wondering how we can use this feature to do something like this:
function f(p1=1, p2, p3, p4, p5=5){
return "{p1: " + p1 + ", p2: " + p2 + ", p3: " + p3 + ", p4: " + p4 + ", p5: " + p5 + "}";
}
var test = f(,20, 30, 40,); //which is not correct
So when I execute it I get this result:
{p1: 1, p2: 20, p3: 30, p4: 40, p5: 5}
Upvotes: 1
Views: 151
Reputation: 665574
Passing undefined
is treated the same as passing nothing (in regard to default values):
f(undefined, 20, 30, 40);
However it is a good practice to only provide default values for the rightmost parameters in a function:
function f(p2, p3, p4, p1=1, p5=5) { … }
f(20, 30, 40);
Upvotes: 4
Reputation: 944564
No. Arguments always fill left to right. You can't skip earlier ones when supplying later ones.
(You can write code, in the function body, which looks at how many arguments you have passed and rearranges them, but there is nothing built-it for doing that).
Upvotes: 1