JavaScript is a fast and non-blocking language. This means it does not wait for one task to finish before moving to the next.
To handle such behaviour, JavaScript uses a powerful concept called a callback function.
In this blog, we’ll understand:
What callbacks are
Why are they important
Real-world examples (including QA/testing use cases)
A callback function is a function that is passed as an argument to another function and is executed later.
Here, sayBye is a callback function that runs after greet finishes its task.
JavaScript handles many tasks that take time, such as:
Instead of stopping everything, JavaScript continues running other code and executes a callback when the task is complete.
Let's take examples from real world.
Think of ordering food
That “action after completion” is a callback.
JavaScript doesn’t wait 3 seconds—it continues and executes the callback later.
Callback functions can be broadly classified based on when and how they are executed.
A synchronous callback is executed immediately during the execution of the main function.
It does not wait or run later.
Teacher checking homework one by one in class
An asynchronous callback is executed later, after a task is completed (like API call, timer, or event).
Ordering food
These callbacks run when a specific event happens(like click, input, hover).
Doorbell
Callbacks that receive values from the main function.
Output:8
Callbacks without a name (most commonly used)
Callbacks with a defined function name
Callback functions are one of the core building blocks of JavaScript, enabling developers to handle tasks that don’t complete instantly—like API calls, timers, and user interactions. By allowing a function to be executed after a specific task is finished, callbacks make JavaScript efficient and non-blocking.
As we’ve seen, callbacks come in different forms—synchronous, asynchronous, event-driven, and more—each serving a specific purpose depending on the situation. They are widely used in real-world applications, especially in scenarios like web development, API handling, and test automation.
However, while callbacks are powerful, overusing or nesting them deeply can make code difficult to read and maintain (known as callback hell). That’s why modern JavaScript introduces alternatives like Promises and async/await, which build on the same concept but provide cleaner and more structured code.
In simple terms, callbacks help you say:
“Run this function when the task is done.”
Understanding callbacks is essential for mastering JavaScript, and once you’re comfortable with them, learning advanced concepts becomes much easier.