Reputation: 167
In a Javascript function with default parameters, is there any way to specify the arguments passed into the function call, by their name, as opposed to their order in the function definition?
function foo(a = 1, b = 2, c = 3){
console.log(a, b, c);
};
foo(); // => 1 2 3
foo(5); // => 5 2 3
foo(b = 5); // => 5 2 3
As you can see, I can change the default parameter I want, only when I insert undefined
in place of the previous arguments:
foo(undefined, b = 5); // => 1 5 3
// which happens to be the same as
foo(undefined, 5); // => 1 5 3
I know that this is possible in Python:
def foo(a = 1, b = 2, c = 3):
print(a, b, c)
foo(b = 5) # => 1 5 3
Is there any way to do this in Javascript without inserting undefined
?
Upvotes: 0
Views: 78
Reputation: 536
First a good practice is to move optional parameters at the end.
In your case you can put the optional parameters in an object specify which attribute of the object you passed like this:
function foo({a=1, b=2, c=3} = {}){
console.log(a, b, c);
};
foo();
foo({b:5})
Upvotes: 1