Set Default Values for Optional Function Parameters in JavaScript
Setting the default value of an optional parameter in a JavaScript function is easy. Since it is perfectly acceptable to call a function in JavaScript with more or less parameters than the function was defined with, you may wish to define every acceptable parameter for your function and set a default value for the truly optional parameters. JavaScript does not have a way of explicitly defining an optional parameter because, it seems, by default all parameters are optional. So how do we find out whether a specific parameter was supplied and, in the case where it was not, set a default value for that specific parameter?
First thing's first, let's define a function that accepts a single parameter and displays it's value in an alert:
function myFunc(myParam) { alert('myParam = ' + myParam); }
Now in running that bit of code you'll notice that it does alert the string value of it's single parameter:
myFunc('myString'); /* alerts "myParam = myString" */ myFunc(5); /* alerts "myParam = 5" */ myFunc(["one", 2, 3, 4]); /* alerts "myParam = one,2,3,4" */ myFunc({ "one" : "1", "two" : "2" }); /* alerts "myParam = [object Object]" */ myFunc(); /* alerts "myParam = undefined" */ myFunc(null); /* alerts "myParam = null */
So say you're in a situation where most of the time you want to alert the message "Hello." but, once in awhile you would like to switch things up and alert the message "Kastor!". It would be easy enough to simply use the function as it is and, you would in fact have what you want. Let's also say that you are feeling lazy and do not want to specify that the message should be "Hello." because you have given your function a descriptive name that practically explains everything the function does. For example:
function sayHelloToEveryoneExceptKastor(myParam) { "use strict"; alert('myParam = ' + myParam); }
So how could we simply call the function and have it say "Hello." without telling it to but, still keep the option to tell it to say "Kastor!"? Well, we will have to define a default value for the parameter of "Hello." of course!
Alright, we want to check for the absence of the argument. From our exploring above we can see that in the absence of the parameter value we saw the alert "undefined". So we could just check to see if(myParam == "undefined")
and if so, alert the message "Hello." But what happens when we want the message to literally say "undefined"? Yes, this sounds weird but it might happen. It is a good thing that the type of an undefined parameter is also undefined, that way we can simply check if(typeof myParam == "undefined")
to cause the alert to say "Hello.". Now, if we want the message to say "undefined" we can supply that as the parameter value and it will work because the type of the parameter will be "string". Let's see how this works:
var myParam; alert(typeof myParam); /* alerts undefined */ myParam = "undefined"; alert(typeof myParam); /* alerts string */ myParam = null; alert(typeof myParam); /* alerts object */ myParam = {}; alert(typeof myParam); /* alerts object */
Integrating what we have figured out so far, we know that if the type of the parameter is undefined then we want the parameter's value to be set to "Hello."
function sayHelloToEveryoneExceptKastor(myParam) { if (typeof myParam == 'undefined') { myParam = "Hello."; } alert('myParam = ' + myParam); }
Doing just the above will solve our problem most of the time. We can simply call sayHelloToEveryoneExceptKastor()
and get the alert "Hello." Alternatively, we can still supply any value for the parameter and it will change the alert to whatever we supplied.
var myParam; sayHelloToEveryoneExceptKastor(); /* alerts "myParam = Hello." */ myParam = "Kastor!"; sayHelloToEveryoneExceptKastor(myParam); /* alerts ""myParam = Kastor!" */ myParam = null; sayHelloToEveryoneExceptKastor(myParam); /* alerts ""myParam = null" */
Now what happens when we have some function like checkDoor()
telling our function when to say hello and when to say something else? You guessed it, when checkDoor()
draws a blank and tells our function that myParam is null then the alert will be "null". This isn't very helpful, we want it to default to saying hello when myParam is null as well.
function checkDoor(guest) { switch (guest) { case "Kastor": return "Kastor!"; case undefined: return null; default: return "Hello."; } } function sayHelloToEveryoneExceptKastor(myParam) { // adding the check to see if myParam is null if (typeof myParam == 'undefined' || myParam === null) { myParam = "Hello."; } // changing the alert to a return value and displaying // a log of results at the end so it is easier to see // what is going on. //alert('myParam = ' + myParam); return myParam; } // Defining a function to test the optional parameter when // it's value is set to: Sally, Bill, Kastor, or null. function testOptionalParam() { var guests, x, checkDoorResult, log, disp, sayHelloToResult; log = ''; guests = ["Sally", "Bill", "Kastor"]; for (x = 0; x < 4; x++) { checkDoorResult = checkDoor(guests[x]); sayHelloToResult = sayHelloToEveryoneExceptKastor(checkDoorResult); log += 'guest name : ' + guests[x] + '\n checkDoorResult : ' + checkDoorResult + '\n sayHelloToResult : ' + sayHelloToResult + '\n'; } disp = document.createElement('div'); disp.style.cssText = 'position: fixed; top: 25%; left: 25%; ' + 'width: 49%; height: 49%; background: black; z-index: 1000; ' + 'overflow: auto; color: #04FF01;'; disp.innerHTML = '<p style="float:right; font-size:48px; ' + 'font-weight:bold; margin:0; padding:0 10px 0 0;">x</p>' + '<pre>' + log + '</pre>'; disp.addEventListener('click', function () { disp.parentNode.removeChild(disp); }); document.body.appendChild(disp); } // Exercising the test. testOptionalParam();
After running the code above, you should see a message displaying the results of the test:
guest name : Sally checkDoorResult : Hello. sayHelloToResult : Hello. guest name : Bill checkDoorResult : Hello. sayHelloToResult : Hello. guest name : Kastor checkDoorResult : Kastor! sayHelloToResult : Kastor! guest name : undefined checkDoorResult : null sayHelloToResult : Hello.
As you can see, when checkDoor returns null, sayHelloToEveryoneExceptKastor will now return "Hello.".
There is a much simpler way of setting the default value of optional parameters in JavaScript. Define a function that takes two parameters: a default value, and a current value. Pass this function both the default you want an optional parameter to have, and the parameter itself. Within this function check if the parameter is either undefined or null and, return the default value if it is. Otherwise, return the parameter as it was passed to the function.
function setAsOptionalArg(defaultVal, optionalArg) { if (typeof optionalArg == 'undefined' || optionalArg === null) { optionalArg = defaultVal; } return optionalArg; }
With the above function defined globally, you will be able to set the default value of an optional parameter easily:
function hasDefaultValues(aParameter, anOptionalParameter) { anOptionalParameter = setAsOptionalArg("default value", anOptionalParameter); return aParameter + anOptionalParameter; } // testing hasDefaultValues for when the optional parameter is passed undefined, null, and "a custom Value" function testHasDefaultValues() { var aParameter, anOptionalParameter; aParameter = 'anOptionalParameter = '; anOptionalParameter = undefined; alert(hasDefaultValues(aParameter, anOptionalParameter)); /* alerts "anOptionalParameter = default value "*/ anOptionalParameter = 'a custom value'; alert(hasDefaultValues(aParameter, anOptionalParameter)); /* alerts "anOptionalParameter = a custom value"*/ anOptionalParameter = null; alert(hasDefaultValues(aParameter, anOptionalParameter)); /* alerts "anOptionalParameter = default value"*/ } testHasDefaultValues();
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.