When should we use callbacks vs directly calling a function?

Question

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?

Answer

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.

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

13 Likes

By example, the function tracks the time it took to run the function it received as a parameter. We could dynamically pass different functions here, which would not be possible if we directly invoked a function within the code block instead.

16 Likes

3 posts were split to a new topic: Callback?

I would say it’s more suitable for dynamic programming. If we can invoke another function, then we can definitely use higher order functions, and it’s similar to functional programming. It’s mostly for manipulating function as values.

1 Like

Callbacks for me are typically seen as functions passed to setTimeout() and setInterval(), and jQuery when we are aspiring for async behaviour. So, as you can see, i only noticed its use in the most complicated scenarios, so your “rules of thumb” are gratefully received.