When should we use callbacks vs directly calling a function?



We learn abut callbacks here. When should we prefer to pass in a function as a parameter vs calling it directly from inside the other function as usual?


One reason that callbacks are helpful is that it allows us not to depend on anything outside of the function itself. This gives us a level of simplicity because everything that the function needs to do its job is either defined in the function or passed in as a parameter. But if we need to use many functions, should we pass them all as callbacks? How should we decide?

I find a helpful rule of thumb is to think of how general the functionality that we’re trying to accomplish is. If the functionality that we want to use is general, for example

  • Say we have a function which selects elements from an array to create a new array according to a rule. This is very general and we may want to change up the rule based on the circumstances.

then this is a situation where we should use callbacks. If we have a function which needs to call another function to perform specific helping behavior, however, it is fine not to use that function as a callback.

We can think of callbacks as variables for functions – they can take on many different function values – whereas calling a function directly is like using a constant.