Specifying one or more arguments as required is one of the common patterns in Javascript. We will see one of the ways in which we can (arguably) make it more simple.
Consider the function below -
1
2
3
4
5
6
|
function getSum(x, y) {
return x + y;
}
console.log(getSum());
// NaN
|
We typically check arguments within function where necessary ..
1
2
3
4
5
6
7
|
function getSum(x, y) {
if (!x || !y) throw "Either x or y is empty. Provide valid values.";
return x + y;
}
console.log(getSum());
// Either x or y is empty. Provide valid values.
|
A simpler way to accomplish the same result -
1
2
3
4
5
6
7
8
9
10
11
12
13
|
function isReqd() {
throw "Argument required. Provide valid value";
}
function getSum(x = isReqd(), y) {
return x + y;
}
console.log(getSum());
//Argument required. Provide valid value.
console.log(getSum(1, 2));
// 3
|
isReqd
is a single function in the module that is used by all other functions to check whether specific required arguments are provided by the caller.