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?
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.
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.
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.
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.
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 ""
.
function parameterTest(bool) { if(typeof bool !== 'undefined') { alert('the parameter exists...'); } else { alert('The parameter doesn\'t exist...'); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With