Skip to content
Advertisement

Allow either named arguments or positional arguments in Javascript

How can I have a function accept either named arguments (foo({a: 'hello', b: 'it is me'})) or positional arguments (foo('hello', 'it is me'))?

I understand that named arguments can be simulated by passing an object to the function:

JavaScript

But that does not allow me to accept positional arguments to be passed.

I would like to use ES6 but anything from ES5 would be ok too.

Advertisement

Answer

First of all, I really would recommend to stick with one approach. As you said, use either “named”

JavaScript

or positional arguments:

JavaScript

Choose the one that fits your function better, do not mix both.


If you really need both for some reason, standard overloading techniques are available to you. It’ll only work properly if your first positional argument is not an object. I would propose one of the following idioms:

JavaScript
JavaScript

and if you need default values, it gets ugly either way:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement