I was wondering, can you create a function with an optional parameter.
Example:
function parameterTest(test)
{
if exists(test)
{
alert(\'t
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
function parameterTest(p) {
if ( p === undefined)
alert('The parameter doesn\'t exist...');
else
alert('the parameter exists...');
}
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>
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 ""
.
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
}
function parameterTest(bool)
{
if(typeof bool !== 'undefined')
{
alert('the parameter exists...');
}
else
{
alert('The parameter doesn\'t exist...');
}
}