For the user's ease, I have a function that receives an optional argument first, before the required argument. For example:
ns.myFunction('optional arg', function(){
//the required callback
});
I'm doing this rather than doing the following since the callback body could be long, and the user might forget to override the defaults to the optional arguments:
ns.myFunction(function(){
//the required callback
}, 'optional arg');
Currently I'm doing this to check:
function myFunction(first, second) {
//if second is undefined and first is a function
if (typeof second === 'undefined' && typeof first === 'function') {
second = first;
}
}
Questions
To indicate optional arguments, Square brackets are commonly used, and can also be used to group parameters that must be specified together. To indicate required arguments, Angled brackets are commonly used, following the same grouping conventions as square brackets.
What are Optional Parameters? By definition, an Optional Parameter is a handy feature that enables programmers to pass less number of parameters to a function and assign a default value.
Optional arguments enable you to omit arguments for some parameters. Both techniques can be used with methods, indexers, constructors, and delegates. When you use named and optional arguments, the arguments are evaluated in the order in which they appear in the argument list, not the parameter list.
This is not the right way because optional parameters are by convention always placed at the end. And you see a reason why: it is much easier to handle them. If the length of anonymous function is your concern, clients of your API should use function references or variables:
function callback1() { //...
var callback2 = function() {//...
myFunction(callbackX, optional);
The problem with escaping this
can be solved with bind()
.
If you really want to go the path of multiple optional parameters and callback at the end, I can think of two ways: arguments
object or wrapping all optional arguments in one options
objects.
With arguments
you can write:
var lastOptionalIndex = arguments.length - 2;
var callback = arguments[lastOptionalIndex + 1]; //required callback is always last
var optionalFirst = lastOptionalIndex >=0? arguments[0] : undefined;
var optionalSecond = lastOptionalIndex >=1? arguments[1] : undefined;
//...
See how ugly it is compared to:
function myFunction(callback, firstOptional, secondOptional //...
With options
wrapper object you always have two arguments:
function myFunction(options, callback);
Where options
is just an object:
{
firstOptional: 1,
secondOptional: 'foo'
//...
}
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