What are callbacks?
- Node.js course
- Beginner
- Lesson 77/116
- 5 min
Learn the callback function concept and usage.
What are callbacks?
A callback is a function passed as an argument to another function, to be called later. The call does not happen right away; it comes when an event completes.
Syntax: function run(cb) { cb(); }. Here cb is a function, and run calls it at the right moment. You define the function; another function runs it for you.
Example: setTimeout(() => console.log('hello'), 1000). The arrow function is a callback; setTimeout calls it after one second. Callbacks are common in delayed and event-driven work.
Call time
The power of callbacks comes from flexible call time. You define the function; the caller decides when and how to invoke it. This is a fundamental pattern in event-driven programming.
Example: function withGreeting(name, cb) { cb('Hello ' + name); }. Here withGreeting passes a value to cb. The caller receives and uses it: withGreeting('Ayşe', msg => console.log(msg)).
This pattern separates the side that prepares the data from the side that uses it. When preparation is done, the callback fires; you can then change each side independently.
Practice Greet with a callback
Define a function withGreeting(name, cb). Its body should call cb('Hello ' + name). Call it as withGreeting('Ayşe', msg => console.log(msg)) so the result prints.
Starter code
// Define withGreeting and call it with a callbackSample solution
function withGreeting(name, cb) {
cb('Hello ' + name);
}
withGreeting('Ayşe', msg => console.log(msg));Expected output
Hello Ayşe
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does callback mean?
- A function called later Correct answer
- A returned value
- An error
- A loop body
Explanation: a callback is a function passed in and called later.
2 Invoke the callback
function run(cb) {
____;
}
function run(cb) {
cb();
}
Explanation: cb() invokes the function passed as a parameter.
3 Match the callback parts
| Term | Meaning |
|---|---|
cb |
Callback parameter |
cb() |
Callback invocation |
() => {} |
Function passed as callback |
setTimeout |
Function using a callback |