I find the named parameters feature in C# quite useful in some cases.
calculateBMI(70, height: 175);
What if I want this in javascript?
What I don't want is -
myFunction({ param1 : 70, param2 : 175});
function myFunction(params){
//check if params is an object
//check if the parameters I need are non-null
//blah-blah
}
That approach I've already used. Is there another way?
I'm okay using any library do this. (Or somebody can point me to one that already does)
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:
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
where
a
andb
are positional arguments and the last argument is an object with named arguments.For example:
Which you would use as:
DEMO
There are some drawbacks to this approach (you have been warned!):
undefined
(that's different from having no value at all). That means you cannot usearguments.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
or even extend
Function.prototype
so that you could do: