How to Require Function Parameter in JS?

In es6 default parameter were added which is a welcome change, but what if you want to throw error if a parameter was not provided.

Well you can do it by calling a closure in default parameter which can throw error for you.

This practice is good if you are having a lot of function with required parameters to debug what went wrong quickly. Otherwise it you can simply show an error from inside the function

const isRequired = (message = null) => {
 let err = (message == null || message.length < 2) ? 'param is required' : `${message[0]} param is required in ${message[1]} function`;
 throw new Error();

const myFunction = (param1 = isRequired(['name', 'myFunction'])) => {
 console.log(`param: ${param1}`)

// These will throw an error

// These are work!

Leave a Reply

Your email address will not be published. Required fields are marked *