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 ();
}
1

3 Answers 3

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;.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
That's true, but it entirely depends on what you're trying to achieve.
Thanks. I used typeof anotherFunction !== "undefined" instead.
1

Just test if a value was passed:

return anotherFunction ? anotherFunction() : true

Comments

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.

3 Comments

You're defining and invoking a function needlessly every time myFunction is called.
A workaround would be to define var trueFn = function() { return true; };, and then use anotherFunction = anotherFunction || trueFn;
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.