JS Required Params
TBH, JavaScript isn’t my favorite coding language. Luckily, ECMAScript 2015 (ES6) added some really useful tricks.
Several languages support the option of enforcing required function arguments. Meaning the program will throw an exception when the function is called without these parameters.
Here is a suggestion for implementing this, using ES6 default parameters.
Say we have our multiply
function:
const multiply = (a, b) => a * b;
We can declare a simple required
function:
const required = () => { throw new Error('Missing required parameter') };
And add it to multiply
’s arguments as a default parameter:
const multiply = (a = required(), b = required()) => a * b;
Calling multiply(3)
will result in:
Error: Missing required parameter