Reputation: 170815
ES2015 introduced default parameters. In other languages with default parameters, they can also usually be named in function calls, to make them more useful when there is more than one:
function foo(baz = 0, bar = 1) { ... }
foo(bar = 3); // baz should be 0
ES2015 doesn't seem to have added this (I'll be happy to learn if I missed it or if a later version does).
There is the old approach of passing an object instead:
function foo(options) {
baz = options.baz || 0;
bar = options.bar || 1;
}
foo({bar: 3}); // baz is 0
What I am looking for is a way to combine them, so I could call either
foo(5) // baz = 5, bar = 1
foo({baz: 5}) // baz = 5, bar = 1
foo({bar: 3}); // baz = 0, bar = 3
foo(5, {bar: 3}); // baz = 5, bar = 3
emulating named arguments from other languages.
Upvotes: 0
Views: 111
Reputation: 64943
This is partially achieved by using object destructuring on input parameters:
// The object being passed is also optional.
// - If you call the function with no parameter,
// it'll be set an empty object so you'll get the default one
// - If you give an object with any of the properties already set
// you either get these values or one of the defaults
const f = ( { x = 11, y = 10 } = {} ) => {
console.log( `${x} ${y}` )
}
f( { y: 20 } )
BTW, you can combine regular parameters with destructured ones, but you can't provide destructurable arguments as if they were regular parameters:
f( 1, { y: 10 } )
won't assign x
.f( { x: 10 }, 2 )
won't assign y
.In addition, you can accept regular and destructured parameters:
const f = ( w, { x = 1, y = 2 } = {}, z = 3 ) =>
console.log( `${w} ${x} ${y} ${z}` )
f( 80, { y: 35 } )
You're forced to give argument maps (i.e. objects). BTW, if you get used with this approach, you almost get the same functionality, excepting the ability to give unnamed positional arguments.
Upvotes: 3
Reputation: 185082
Can be made to work in this instance, but probably not worth it. Use Matías Fidemraizer's approach.
const foo = (arg1, arg2) =>
{
let args = { baz: 0 , bar: 1 };
if (typeof arg1 == 'number')
args.baz = arg1;
else
Object.assign(args, arg1);
if (typeof arg2 == 'number')
args.bar = arg2;
else
Object.assign(args, arg2);
console.log(args);
}
foo(5) // baz = 5, bar = 1
foo({baz: 5}) // baz = 5, bar = 1
foo({bar: 3}); // baz = 0, bar = 3
foo(5, {bar: 3}); // baz = 5, bar = 3
Upvotes: 1