Leave your number, I'll call you back
Day 51 of 149
👉 Full deep-dive with code examples
The Phone Call
You call a busy restaurant for a reservation.
Bad: "Please hold..." (wait on the line for 30 min) 😫
Better: "Leave your number, we'll call you back when ready!"
You hang up, do other things. They call when ready!
In Code
// "Call me back when you're done"
fetchData(function (result) {
console.log("Got the data!", result);
});
// Meanwhile, do other things!
console.log("I'm not waiting!");
Output:
I'm not waiting!
Got the data! {...}
The callback runs WHEN the data arrives, not before!
Why Callbacks?
JavaScript can't wait! If it paused for every slow thing:
- Fetching data: a couple of seconds... frozen
- Loading images: a few seconds... frozen
- User can't click anything! 😤
Callbacks: "Keep going, I'll handle it when ready."
The Problem: Callback Hell
Nested callbacks get ugly:
getData(function (a) {
getMore(a, function (b) {
getEvenMore(b, function (c) {
// Help! 🆘
});
});
});
This is why Promises were invented!
In One Sentence
Callbacks are functions you pass to be called later when an operation completes, instead of waiting.
🔗 Enjoying these? Follow for daily ELI5 explanations!
Making complex tech concepts simple, one day at a time.
Top comments (0)