Callbacks are the original control-flow hook in JavaScript. The production issues are inversion of control, callback hell, and debugging legacy async code that cannot cancel or compose cleanly.
What are callbacks in JavaScript?
The Core Idea
A callback is a function you hand to other code so it can run later. That sounds simple, but the production/debug issue is inversion of control: another API decides when your function runs, what error path it takes, and whether it can be canceled or composed cleanly.
// Example: synchronous callback
function greet(name) {
console.log('Hello, ' + name);
}
function processUserInput(callback) {
const name = 'Alice';
callback(name);
}
processUserInput(greet); // Hello, Alice
Callbacks in Asynchronous Code
Callbacks are also used to handle tasks that take time (like network requests or file loading), so the program can keep running while waiting for them to finish.
console.log('Start');
setTimeout(function() {
console.log('This runs later');
}, 1000);
console.log('End');
// Output: Start → End → This runs later
Concept | Explanation | Example |
|---|---|---|
Synchronous Callback | Executed immediately during the function call. |
|
Asynchronous Callback | Executed later, after a delay or async operation finishes. |
|
Callback Hell | When many callbacks are nested inside each other, making code hard to read. |
|
Practical notes
Watch for edge case behavior, common pitfalls, and trade-offs between clarity and performance. Mention accessibility and testing considerations when the concept affects UI output or event timing.
Think of callbacks like leaving your phone number with someone: you don’t wait on the line — they’ll call you back when they’re ready.
- A callback is a function passed as an argument to another function.
- Allows asynchronous and event-driven behavior.
- Can cause 'callback hell' when deeply nested — use Promises or async/await instead.
- Core part of how JavaScript handles non-blocking operations.
Use the relevant interview-question hub first, then move into a concrete study plan before targeted company sets.