Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 671
Guido Visser Avatar asked Oct 22 '12 20:10

Guido Visser


People also ask

How do you check if a parameter is a function in Javascript?

To check if a variable is of type function, use the typeof operator, e.g. typeof myVariable === 'function' . The typeof operator returns a string that indicates the type of the value. If the type of the variable is a function, a string containing the word function is returned.

Can we use parameter in function?

A function can take parameters which are just values you supply to the function so that the function can do something utilising those values. These parameters are just like variables except that the values of these variables are defined when we call the function and are not assigned values within the function itself.

How do you test if a function is defined?

Use the typeof operator to check if a function is defined, e.g. typeof myFunction === 'function' . The typeof operator returns a string that indicates the type of a value. If the function is not defined, the typeof operator returns "undefined" and doesn't throw an error.

Are the parameters received by functions?

Function Parameters and Arguments Function parameters are the names listed in the function definition. Function arguments are the real values passed to (and received by) the function.


2 Answers

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

like image 123
Denys Séguret Avatar answered Sep 17 '22 12:09

Denys Séguret


function parameterTest(bool) {    if(typeof bool !== 'undefined')    {      alert('the parameter exists...');    }    else    {      alert('The parameter doesn\'t exist...');    } } 
like image 31
Johan Avatar answered Sep 20 '22 12:09

Johan