category | created | tags | title |
---|---|---|---|
Trick |
2021-02-24 |
JavaScript |
Enforce required parameters |
In ES6, the default value of a parameter is evaluated if the parameter is missing. It allows us to enfore that a given parameter is required.
const required = () => {
throw new Error('Missing parameter');
};
const getAges = (yearOfBirth = required()) => new Date().getFullYear() - yearOfBirth;
Calling getAges()
without parameter will throw the exception Missing parameter
.