How to test if a parameter is provided to a function?

This is a very frequent pattern.

You can test it using

function parameterTest(bool) {
  if (bool !== undefined) {

You can then call your function with one of those forms :

 parameterTest();
 parameterTest(someValue);

Be careful not to make the frequent error of testing

if (!bool) {

Because you wouldn't be able to differentiate an unprovided value from false, 0 or "".


In JavaScript, if you neglect to give a parameter it will default to undefined.

You could try it out for yourself easily enough, either in your browser console or using JSFiddle.

You can check for the existance of the parameter, as you say, and that way write a function that can use a parameter or not. However, JavaScript Garden (a great resource) recommends staying away from typeof in most other cases, as its output is just about useless (check out the table of results of typeof).


function parameterTest(bool)
{
   if(typeof bool !== 'undefined')
   {
     alert('the parameter exists...');
   }
   else
   {
     alert('The parameter doesn\'t exist...');
   }
}