What are callback functions and how are they used?
TL;DR
A callback is a function supplied to other code to be invoked according to that API's contract. Some callbacks run synchronously, such as an Array.prototype.map() callback; others run later, such as timer, event, or I/O callbacks. Passing a callback does not by itself make an operation asynchronous.
Definition
A callback function is passed to other code so that code can invoke it at the defined time. The invocation may be synchronous or asynchronous; only an asynchronous API allows the current stack to finish before the callback runs.
Synchronous callbacks
Synchronous callbacks are executed immediately within the function they are passed to. They are often used for tasks that need to be completed before moving on to the next line of code.
Asynchronous callbacks
Asynchronous callbacks are used for operations that take some time to complete, such as reading files, making HTTP requests, or handling events. These callbacks are executed after the asynchronous operation has finished.
Common use cases
Event handling
Callbacks are often used in event handling. For example, in JavaScript, you can pass a callback function to an event listener.
API calls
Callbacks are frequently used in making API calls to handle the response data.
Timers
Callbacks are also used with timers like setTimeout and setInterval.
Further reading
- MDN Web Docs: Callback function
- JavaScript.info: Callbacks
- Eloquent JavaScript: Asynchronous Programming