In JavaScript, a callback function is a function that is passed as an argument to another function and executed later. Callback functions are commonly used to handle asynchronous operations such as API requests, timers, and event handling.
Callbacks allow developers to control the order in which code is executed. Instead of running everything at once, JavaScript can execute a function only when a specific task is completed.
What is a Callback Function?
A callback function is simply a function that is given to another function so that it can be executed at the appropriate time.
Hello Rahul
Goodbye!
In this example, the function sayBye is passed as a callback to the greet function and executed after the greeting message.
Why Callback Functions are Used
Callback functions help manage tasks that take time to complete. For example, when fetching data from a server, JavaScript does not stop the entire program. Instead, it continues running other code and executes the callback when the data is ready.
Callback Example with setTimeout
The setTimeout() function is a common example of a callback in JavaScript. It executes a function after a specified delay.
This message appears after 2 seconds
Callback with Array Methods
Callbacks are frequently used with array methods such as forEach(), map(), and filter().
1
2
3
Anonymous Callback Functions
Often, callback functions are written as anonymous functions, meaning they do not have a name.
Processing user...
User processed successfully
Advantages of Callback Functions
- Allow asynchronous programming
- Help control execution order
- Make code flexible and reusable
- Commonly used in event handling and API requests
Conclusion
Callback functions are an essential concept in JavaScript programming. They allow functions to be passed as arguments and executed later, making asynchronous programming possible.
Callbacks are widely used in real-world JavaScript applications for tasks such as handling events, processing API responses, and managing timers.
In the next tutorial, you will learn about Promises in JavaScript, which provide a more structured way to handle asynchronous operations and avoid callback complexity.

