A callback is a function that is passed as an argument to another function and is executed later, after some task is completed.
Callbacks are one of the earliest ways JavaScript handled asynchronous operations. They are commonly used when working with timers, events, and server requests.
Understanding callbacks helps students learn how JavaScript handles tasks that take time to complete.
Why Callbacks Are Used
- To run code after a task finishes
- To handle asynchronous operations
- To control the flow of execution
- To respond to events and user actions
- To work with APIs and data loading
Callbacks allow JavaScript to stay responsive.
Here, sayBye is passed as a callback to the greet function.
After greeting the user, the callback function runs automatically.
The function inside setTimeout is a callback.
It runs only after the given time delay.
These examples show how callbacks allow code to run after an operation finishes.
By mastering callbacks, students gain the foundation needed to understand promises and async/await in modern JavaScript development.