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.
function fetchData(callback) {setTimeout(() => {const data = { name: 'John Doe' };callback(null, data);}, 0);}function handleData(error, data) {if (error) throw error;console.log(data);}fetchData(handleData);
What are callback functions and how are they used?
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.
function greet(name, callback) {console.log('Hello ' + name);callback();}function sayGoodbye() {console.log('Goodbye!');}greet('Alice', sayGoodbye);// Output:// Hello Alice// Goodbye!
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.
function fetchData(callback) {setTimeout(() => {const data = { name: 'John Doe' };callback(data);}, 1000);}function handleData(data) {console.log(data);}fetchData(handleData);// Output: { name: 'John Doe' } after 1 second
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.
const button = document.createElement('button');button.addEventListener('click', () => {setTimeout(() => {console.log('Button clicked after 1s');}, 1000);});button.click();
API calls
Callbacks are frequently used in making API calls to handle the response data.
function getUserData(userId, callback) {fetch(`https://jsonplaceholder.typicode.com/todos/${userId}`).then((response) => {if (!response.ok) throw new Error(`HTTP ${response.status}`);return response.json();}).then((data) => callback(data)).catch((error) => console.error('Error:', error));}function displayUserData(data) {console.log(data);}getUserData(1, displayUserData);
Timers
Callbacks are also used with timers like setTimeout and setInterval.
function sayHello() {console.log('Hello, world!');}setTimeout(sayHello, 2000); // After 2 seconds elapse, sayHello callback is called
Further reading
- MDN Web Docs: Callback function
- JavaScript.info: Callbacks
- Eloquent JavaScript: Asynchronous Programming