I think you are abusing the functionality a little bit.
The point of default parameters is providing a value which make sense in case calls to this function don't pass some definite value for that parameter.
There is a big overlap between not passing a definite value and forgetting a mandatory parameter, but there is a difference: you can pass undefined
.
Your code will throw if the function is called with undefined
:
const mandatory = (name) => {
throw new Error(`The ${name} parameter is mandatory`);
};
const foo = (bar = mandatory('bar')) => {
// some code
};
foo(undefined); // Error: The bar parameter is mandatory
In this case complaining about the parameter being mandatory is misleading, because a parameter has been passed indeed.
undefined
might not be an allowed value, but in this case you should check the value and complain about its type.
If you only want to check if an argument has been passed or not, using a normal function and checking arguments.length
may be a better idea.
See for example the behavior of DOMParser#parseFromString
, which in my opinion is more helpful:
var p = new DOMParser();
p.parseFromString(); // TypeError: Not enough arguments
p.parseFromString(undefined); // TypeError: Not enough arguments
p.parseFromString(undefined, undefined); // TypeError: Argument 2 'undefined' is not a valid value