Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Make function parameters required in vanilla JavaScript

You might be aware of how to set default values for function parameters in JavaScript. For instance, if you want to set the default value for a parameter, you can do it like so.

function say(message='Hi') {
    console.log(message);
}

say(); // 'Hi'
say(undefined); // 'Hi'
say('Hello'); // 'Hello'

This is fine. But do you know there’s a trick using which you can make function parameters required?

I came to know about this trick while reading 7 Useful JavaScript Tricks. So, according to this, there would be a function that would just throw a standard error and you can further assign this function to the function parameter like so.

const isRequired = () => {
    throw new Error('param is required');
};

const hello = (name = isRequired()) => {
    console.log(`hello ${name}`)
};

This makes the parameter name required. Meaning, it will throw an error if the parameter is left empty or assigned undefined like so.

// This will throw an error because no name is provided
hello();

// This will also throw an error
hello(undefined);

// These are good!
hello(null);
hello('Wordl!');

This is pretty useful and comes handy at times!

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?