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

JavascriptFunction

Javascript Problem Overview


I was wondering, can you create a function with an optional parameter.

Example:

function parameterTest(test)
{
   if exists(test)
   {
     alert('the parameter exists...');
   }
   else
   {
     alert('The parameter doesn\'t exist...');
   }
}

So if you call parameterTest() then the result would be a message "The parameter doesn't exist...". And if you call parameterTest(true) then it would return "the parameter exists...".

Is this possible?

Javascript Solutions


Solution 1 - Javascript

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 "".

Solution 2 - Javascript

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

Solution 3 - Javascript

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).

Solution 4 - Javascript

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

Solution 5 - Javascript

best way to check: if the param is not undefined

function parameterTest(param) {
    if (param !== undefined)
    ...

the param could be also a variable or a function name

Solution 6 - Javascript

init default values if not exists:

function loadDialog(fn, f, local, anim) {
  switch (arguments.length) {  
    case 1: f=null;
    case 2: local=false;
    case 3: anim=false;
  }
  ...
}

Solution 7 - Javascript

None of these answers were doing it for me. I needed to know if someone had used the parameter or not. If someone invoked the function passing undefined I wanted to treat that as them using that value as the parameter. Anyway, the solution was quite easy using some modern JS:

function parameterTest(...test) {
  if (test.length) {
    return `exists`;
  } else {
    return `not exists`;
  }
}

parameterTest(123);         // exists
parameterTest(undefined);   // exists
parameterTest();            // not exists
parameterTest(window.blah); // exists

For older browsers you can use arguments:

function parameterTest() {
  if (arguments.length) {
    return "exists";
  } else {
    return "not exists";
  }
}

Solution 8 - Javascript

null == undefined is true

if (arg == null){
    // arg was not passed.
}

Code example:

var button = document.querySelector("button");

function myFunction(arg){
  if(arg == null){
    alert("argument was not passed.");
  } else {
    alert("argument " + arg + " was passed.");
  }
}

<button onclick="myFunction('foo');">click to fire function w arg</button>
<br><br>
<button onclick="myFunction();">click to fire function w/o arg</button>

Solution 9 - Javascript

I know this is old, but this is my preferred way to check, and assign default values to functions:

function testParamFunction(param1, param2) {
    param1 = typeof param1 === 'undefined' ? null : param1;
    param2 = typeof param2 === 'undefined' ? 'default' : param2;
    
    // exit if the required parameter is not passed
    if (param1 === null) {
        console.error('Required parameter was not passed');
        return;
    }

    // param2 is not mandatory and is assigned a default value so 
    // things continue as long as param1 has a value
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGuido VisserView Question on Stackoverflow
Solution 1 - JavascriptDenys SéguretView Answer on Stackoverflow
Solution 2 - JavascriptJohanView Answer on Stackoverflow
Solution 3 - JavascriptJohanna LarssonView Answer on Stackoverflow
Solution 4 - JavascriptmanmanView Answer on Stackoverflow
Solution 5 - JavascriptungalcrysView Answer on Stackoverflow
Solution 6 - JavascriptZPKSoft Paweł KrzyżanowskiView Answer on Stackoverflow
Solution 7 - JavascriptJamie TwellsView Answer on Stackoverflow
Solution 8 - JavascriptRonnie RoystonView Answer on Stackoverflow
Solution 9 - JavascriptAdam JowettView Answer on Stackoverflow