Skip to content
Advertisement

Is there a way to provide named parameters in a function call in JavaScript?

I find the named parameters feature in C# quite useful in some cases.

JavaScript

What can I use if I want this in JavaScript?


What I don’t want is this:

JavaScript

That approach I’ve already used. Is there another way?

I’m okay using any library to do this.

Advertisement

Answer

ES2015 and later

In ES2015, parameter destructuring can be used to simulate named parameters. It would require the caller to pass an object, but you can avoid all of the checks inside the function if you also use default parameters:

JavaScript

ES5

There is a way to come close to what you want, but it is based on the output of Function.prototype.toString [ES5], which is implementation dependent to some degree, so it might not be cross-browser compatible.

The idea is to parse the parameter names from the string representation of the function so that you can associate the properties of an object with the corresponding parameter.

A function call could then look like

JavaScript

where a and b are positional arguments and the last argument is an object with named arguments.

For example:

JavaScript

Which you would use as:

JavaScript

DEMO

There are some drawbacks to this approach (you have been warned!):

  • If the last argument is an object, it is treated as a “named argument objects”
  • You will always get as many arguments as you defined in the function, but some of them might have the value undefined (that’s different from having no value at all). That means you cannot use arguments.length to test how many arguments have been passed.

Instead of having a function creating the wrapper, you could also have a function which accepts a function and various values as arguments, such as

JavaScript

or even extend Function.prototype so that you could do:

JavaScript
Advertisement