What is a callback function?
A callback function is a function passed as an argument to another function, so it runs later, after some event happens or an operation finishes.
In other words:
"I'm handing you a function, call it when you're ready."
The simplest example
function sayHello(name) {
console.log(`Hello, ${name}!`);
}
function greet(callback) {
console.log('Getting ready to say hello...');
callback('Tim');
}
greet(sayHello);What happens:
sayHellois the callback passed intogreet;greetcalls it internally;- The console prints:
Getting ready to say hello...
Hello, Tim!Callback as an anonymous function
You don't have to pass a named function, you can pass an anonymous one:
setTimeout(() => {
console.log('2 seconds have passed');
}, 2000);Here:
() => console.log(...)is the callback function,- It will be called after 2 seconds, not right away.
How this works
- JavaScript accepts a callback as a value (since functions are "first-class objects");
- It does not call it right away, but stores it for a later call;
- When the right moment comes (a timer fires, a request finishes, an event happens), the engine calls that function.
Real-world examples
1. Callback in an event handler
button.addEventListener('click', () => {
console.log('Button clicked!');
});Here the callback is called by the browser on a click.
2. Callback when loading data
fetch('/user')
.then(response => response.json())
.then(data => console.log(data));The .then() callbacks are called after the asynchronous request finishes.
3. Callback as a step in an algorithm
function calculate(a, b, callback) {
const result = a + b;
callback(result);
}
calculate(2, 3, (sum) => {
console.log('Result:', sum);
});The problem: "Callback Hell"
If there are too many callbacks, the code becomes nested and unreadable:
getUser(id, user => {
getPosts(user, posts => {
getComments(posts, comments => {
console.log('Done!');
});
});
});This is called callback hell.
Solving the problem
To avoid "hellish" nesting, we got:
-
Promises:
javascriptgetUser(id) .then(getPosts) .then(getComments) .then(console.log); -
async/await:javascriptconst user = await getUser(id); const posts = await getPosts(user); const comments = await getComments(posts); console.log('Done!');
A simple analogy
Imagine you're ordering a pizza. You say: "Call me when it's ready."
That "call" is the callback.
SUMMARY
| Term | Description |
|---|---|
| Callback function | A function passed into another function to run later |
| When it's called | After an event, an operation finishes, or a condition is met |
| Usage examples | setTimeout, addEventListener, fetch().then() |
| Problem | Deep nesting ("callback hell") |
| Modern alternatives | Promise, async/await |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.