What is callback?
A callback is a function that you pass as an argument to another function, with the intention that the receiving function will “call back” (execute) it later, usually after it finishes some work like fetching data or waiting for a timer.
Let's break it down
- Think of a callback like leaving a note for a friend: you give them the note (the function) and ask them to read it when they’re done with their current task.
- In code, you write a function (the callback) and hand it to another function. The receiving function stores it and runs it at the appropriate moment.
- The callback can receive results or errors from the original operation, allowing you to decide what to do next.
Why does it matter?
Callbacks let programs handle tasks that take time (like network requests) without freezing the whole app. They enable asynchronous behavior, keeping the user interface responsive and allowing multiple operations to run in parallel.
Where is it used?
- Web browsers: handling button clicks, loading images, or waiting for AJAX responses.
- Node.js: reading files, querying databases, or setting timers.
- Any language with asynchronous APIs, such as Python’s asyncio, Java’s CompletableFuture, or C#‘s delegates.
Good things about it
- Simple to understand: just a function passed around.
- Keeps code non‑blocking, improving performance and user experience.
- Flexible: you can pass different callbacks to the same function to get varied behavior.
Not-so-good things
- Can lead to “callback hell” where many nested callbacks become hard to read and maintain.
- Error handling can be tricky; you must remember to pass errors to the callback.
- Modern alternatives like Promises and async/await often provide clearer, more linear code structures.