Using Default Parameter to enforce a required Parameter

Sujeet Kumar Jaiswal
Sujeet’s Blog
Published in
2 min readOct 6, 2017

Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed. We can use this fact to enforce a required parameter as well.

Understanding the need

Let us take the below example, which appends a value to an array. Array is an optional parameter which default to an empty array. But value must be provided to ensure something is appended.

function append(value, array = []) {
array.push(value);
return array;
}
append(1); //[1]
append(2); //[2], not [1, 2]
append(); // [undefined]
// I want append() to throw error and enforce to pass atleast value

Since we want to enforce the value to be always provide while calling the function, we need to throw error whenever value is not provided.

Solution

We know that if we use default parameter, it will be computed only if nothing is passed. So we will create a function whose return value is assigned to value, but this function instead of returning anything, it will raise an error.

The above method is far better than testing its availability in the function code and throwing error

// In general
function append(value, array = []){
if(value == undefined){
throw new Error('value is a required parameter')
}
...
}

References:

  1. MDN Default parameters (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters)
  2. How Default Parameters Work in JavaScript (ES 6) — freeCodeCamp

--

--