-1
\$\begingroup\$

Say I have a method that takes an optional param that is a callback function. At some point in the method, if that function exists, I should call it. Is there a best practice for doing this?

I like this approach: !!callback && callback();

But I've seen it's simplier form callback && callback(); which feels wrong (because it's not explicitly converting callback to a boolean).

I could of course use typeof and/or if, but those seem unnecessarily verbose.

I've googled around a bit, but I'm not seeing anything concrete on this subject. Does a best practice for this scenario exist?

\$\endgroup\$
2
\$\begingroup\$

A good way to avoid this issue is to not have optional parameters, or at least have default values for them.

For example:

const emptyFn = () => {} 

function doStuff(callback = emptyFn){
    callback()
}

But other than that, callback && callback() is pretty well known way of doing this sort of thing, so it's not too bad imo.

\$\endgroup\$
  • \$\begingroup\$ function doStuff(callback = () => {}) also works and avoids having another symbol in the namespace. If one had multiple functions all having a parameter defaulting to the empty function, I would go with your solution, however. \$\endgroup\$ – ComFreek Mar 14 '18 at 8:47

Not the answer you're looking for? Browse other questions tagged or ask your own question.