Brian's Blog

items I see across my tribes

Optional parameters in Javascript functions

January 04
by briancarter 4. January 2012 08:49

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.

Categories: Development


 Questions or Feedback, my contact information is located on my About page.


The opinions, thoughts, and comments made in these blog posts are solely my own (unless otherwise stated). They do not reflect the opinions, thoughts or practices of my employer, my universities, my family, or anyone else. Also, I retain the right to change my mind about anything I publish here without having to go back and edit posts that occurred in the past. 

These are my opinions, or just as likely, someone else's opinions that I leveraged for my own.