A callback is a function passed as an argument to another function to be executed later, often after a task is completed. Covers: async, callbacks, event loop, functions, higher order functions.
What are callbacks in JavaScript?
Use guided tracks for structured prep, then practice company-specific question sets when you want targeted interview coverage.
The Core Idea
A callback is simply a function passed into another function as an argument, to be called back later when a certain task finishes. It’s a fundamental pattern in JavaScript, especially in asynchronous programming.
// 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.