C#, for example, allows using named parameters like so:
calculateBMI(70, height: 175);
I find this quite useful. How can I get a similar effect in JavaScript?
I’ve tried doing things like
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
}
but it seems awkward. Is there a simpler way?
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
aandbare 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.lengthto 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.prototypeso that you could do: