# Best Practice: check if a function exists before calling it [closed]

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?

## 1 Answer

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.

• 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. – ComFreek Mar 14 '18 at 8:47