This content originally appeared on Bits and Pieces - Medium and was authored by Aquib Afzal
In JavaScript, a callback function is a function that is passed as an argument to another function and is executed after some operation has been completed.
Callbacks allow us to write asynchronous code, where we can continue to execute other code while waiting for a particular event to occur.
How Do Callback Functions Work?

Callback functions are used to handle events that may occur at any point in time. By passing a callback function as an argument, we allow the function to call it when necessary.
For example, we have to execute doSomethingElse function just after logging “Doing something…” which is in function doSomething.
function doSomething(callback) {
console.log('Doing something...');
callback();
}
function doSomethingElse() {
console.log('Doing something else...');
}
doSomething(doSomethingElse);
In this example, we define two functions, doSomething and doSomethingElse. The doSomething function takes a callback function as an argument and logs a message to the console. It then calls the callback function. The doSomethingElse function logs a different message to the console.
Finally, we call the doSomething function and pass in the doSomethingElse function as the callback. When doSomething is called, it logs "Doing something..." to the console and then calls the doSomethingElse function, which logs "Doing something else..." to the console.
Real-World Example
Another real-world example of using a callback function is when fetching data from a server. In this case, we use a callback function to handle the data once it has been received.
function fetchData(url, callback) {
fetch(url)
.then(response => response.json())
.then(data => callback(data))
.catch(error => console.log(error));
}
fetchData('https://jsonplaceholder.typicode.com/todos/1', function(data) {
console.log(data);
});
In this example, we define a function fetchData that takes a URL and a callback function as arguments. The function uses the fetch function to make a network request to the specified URL. Once the data is received, it is converted to JSON and the callback function is called with the data as an argument.
Finally, we call the fetchData function and pass in a callback function that logs the data to the console. When the data is received from the server, the callback function is called with the data, and the data is logged to the console.
Issues with Callback Functions and Solutions

One issue that can arise when using callback functions is the problem of “callback hell” or “pyramid of doom.” This occurs when you have multiple nested callbacks, making the code difficult to read and understand.
One solution to this problem is to use promises or async/await, which allow for more structured and readable code.
Conclusion
Callbacks are a powerful tool in programming, allowing for asynchronous code execution and enabling developers to write more efficient and flexible code.
However, they can also make code difficult to read and understand, especially when there are multiple nested callbacks.
Promises and async/await are two alternatives to using callbacks that can make code more readable and maintainable.
Build Apps with reusable components, just like Lego

Bit’s open-source tool help 250,000+ devs to build apps with components.
Turn any UI, feature, or page into a reusable component — and share it across your applications. It’s easier to collaborate and build faster.
Split apps into components to make app development easier, and enjoy the best experience for the workflows you want:
→ Micro-Frontends
→ Design System
→ Code-Sharing and reuse
→ Monorepo
Learn more
- How We Build Micro Frontends
- How we Build a Component Design System
- Bit - Component driven development
- 5 Ways to Build a React Monorepo
- How to Create a Composable React App with Bit
- Sharing JavaScript Utility Functions Across Projects
Callback Functions in JavaScript: A Comprehensive Guide was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Bits and Pieces - Medium and was authored by Aquib Afzal

Aquib Afzal | Sciencx (2023-02-17T12:20:10+00:00) Callback Functions in JavaScript: A Comprehensive Guide. Retrieved from https://www.scien.cx/2023/02/17/callback-functions-in-javascript-a-comprehensive-guide/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.