In JavaScript, how can I create a function with an optional parameter?
Actually, all parameters are optional in JS functions. There is no warning or error if you omit a parameter.
You can set defaults like
function throw_cat(dist){
dist = typeof dist=='undefined' ? 20 : dist;
//OR
dist = dist || 20; //this will assign it to 20 if you pass 0 or another 'falsy' value, though. May be good if you expect a string. String '0' stays, '' or null assigns the default
//etc...
}
There is no syntax in Javascript that specifies that a parameter is optional (or required). All parameters are optional. If they aren't specified they're undefined
so you need to check for that. For example, this function will in effect create a default value of 10 for the parameter:
function myfunc(someParam) {
if (someParam === undefined) {
someParam = 10;
}
...
}
Also you can access the parameters programmatically using the arguments
property.
Lastly, if you have more than about 3-4 parameters it's generally advisable to use an anonymous object instead.
You can use annotation such as {Object=} or {number=} in the comment section when using a doclet:
/** * @param {object=}xyz */
Modern IDE knows to recognize annotations for JavaScript and shows you indications about potential problems in your code.
Example:
/**
*
* @param query
* @param callback
* @param {number=} ttl optional time-to-leave
*/
loadByJSONP:function loadByJSONP(query, callback, ttl) {
...do some work
}
In this example 'ttl' is optional. the annotation {number=} indicate to IDE that this parameter is optional. Accordingly when you call this function with two parameters only, you will not get warning.
Annotations can also be used for designating the expected type. this makes your code better and less prone to bugs. Here is the link for annotations:
https://developers.google.com/closure/compiler/docs/js-for-compiler
First, everyone who writes JavaScript, do yourself a favor and go through Learning Advanced JavaScript from John Resig.
function myFunc(arg1, arg2 /* varargs... */) {
var optional = Array.prototype.slice.call( arguments, 2 );
Every parameter to a function is "optional", even those you declare in the parameter list of the function declaration.
Just consider documenting them well.