How to Make Parameters Required in JavaScript
A nice and easy way to make your parameters mandatory and make sure that no one can call functions without them is by using the below function:
// Making function parameter mandatory:
const isRequired = () => throw new Error('Parameter is required');
const sayHi = (to = isRequired()) => {
console.log(`hello ${to}`);
};
// Calling sayHi without a parameter
sayHi();
// Results in the following error:
// Uncaught Error: Parameter is required
This is achieved by using default parameters. If you don't provide the parameter, it will default to the function which throws an error.
Default parameters are not supported in IE, so if you need to provide support, make sure you either use a polyfill, or alternatively use another approach:
const sayHi = (to) => {
if(arguments.length < 1) {
throw new Error('Parameter is required');
}
console.log(`hello ${to}`);
};
This solution utilizes the arguments
object, which is accessbile to functions, and contains information on the passed arugments.
Resources:
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: