How to Make Parameters Required in JavaScript

How to Make Parameters Required in JavaScript

Ferenc Almasi β€’ 2020 August 13 β€’ Read time 1 min read
  • twitter
  • facebook
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:

Copied to clipboard! Playground
// 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
required-params.js

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:

Copied to clipboard! Playground
const sayHi = (to) => {
    if(arguments.length < 1) {
        throw new Error('Parameter is required');
    }

    console.log(`hello ${to}`);
};
required-params.js

This solution utilizes the arguments object, which is accessbile to functions, and contains information on the passed arugments.

How to Make Parameters Required in JavaScript
If you would like to see more Webtips, follow @flowforfrank

Resources:

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.