22 December 2011

JS - Optional function parameters

Sometimes you want to call the same JavaScript function with a different number of parameters, to replicate the overloading we use in, for instance, .NET. This is how to do it:
function setMenu(param1, param2){
  if(param2 === undefined){
    param2 = -1;
  }
  //Code
}
You can call this function in multiple ways:
setMenu(0, 5);
setMenu(0); //Param2 will be set to '-1' by the function
And both will work.

No comments:

Post a Comment