1

What would be the standard way to define a function which has an optional argument, which itself is a function?

For example I want anotherFunction() to return true, if it's not defined.

function myFunction ( anotherFunction ) {
    /*
    some code here
    */
    return anotherFunction ();
}
vahidseo
  • 371
  • 1
  • 3
  • 16

3 Answers3

2
function myFunction ( anotherFunction ) {
    /*
    some code here
    */
    return (typeof anotherFunction == "function") ? anotherFunction() : true;
}

This has the side effect of making sure the arguement is a function and not some garbage. If you'd prefer to throw, just use return anotherFunction ? anotherFunction() : true;.

Lucas Trzesniewski
  • 50,214
  • 11
  • 107
  • 158
  • The "additional benefit" isn't an additional benefit. If you function expects an argument which is a function, it *should* raise an error if a non-function is passed in. It's better to detect that and fail early, than for the function to happily proceed, disguising the bug. – user229044 Jun 28 '14 at 18:28
  • That's true, but it entirely depends on what you're trying to achieve. – Lucas Trzesniewski Jun 28 '14 at 18:29
  • Thanks. I used typeof anotherFunction !== "undefined" instead. – vahidseo Jun 28 '14 at 18:39
1

Just test if a value was passed:

return anotherFunction ? anotherFunction() : true
user229044
  • 232,980
  • 40
  • 330
  • 338
1

I'd use

function myFunction ( anotherFunction ) {
    anotherFunction = anotherFunction || function(){ return true; };
    /*
    some code here
    */
    return anotherFunction ();
}

This corresponds to the OP's desire to default the optional parameter with a function, not merely making myFunction return true.

Peter Herdenborg
  • 5,736
  • 1
  • 20
  • 21
  • You're defining and invoking a function needlessly every time `myFunction ` is called. – user229044 Jun 28 '14 at 18:31
  • A workaround would be to define `var trueFn = function() { return true; };`, and then use `anotherFunction = anotherFunction || trueFn;` – Lucas Trzesniewski Jun 28 '14 at 18:32
  • True. It may not be the best idea to do this from a performance point of view but conceptually I think it's the most accurate approach. In the general case, the default function could be more meaningful than merely returning true. – Peter Herdenborg Jun 28 '14 at 18:33