Most programming languages have a mechanism which allows optional parameters to be passed to a function/method and if they are not included in the call, default values are set.
This is not the case in Javascript. But thankfully, it is still possible to set up a function that take optional parameters. Consider a function defined like so:
function myFuncName(param1, param2) {In Javascript, it is perfectly legal to make a call to this function in any of three ways:
myFuncName(1, 2);
myFuncName(1);
myFuncName();
They will all work. In javascript, if you want the parameter to be optional, you need to add code in the function itself to deal with the cases when a parameter value is not given in the call. For example, consider the function above where we want to make the second parameter optional and if the second parameter is not given, we set a default value of '3.14'. That can be done like so:
function myFuncName(param1, param2) {
// Set the optional parameter if needed
if ( param2 === undefined ) {
param2 = '3.14';
}
...
}
You can do this for as many parameters as you like, but you need to be sure to order the parameters so that the "most optional" ones are further to the right since as soon as you leave off one parameter, it starts removing values from the right-hand side of the parameter list.