Skip to main content

Command Palette

Search for a command to run...

πŸ“ž Callbacks Explained Like You're 5

Published
β€’2 min read
S

Building AI systems and writing about how they actually work. Master of AI @ University of Technology Sydney. Previously B.Tech CS with focus on IoT. I believe the best way to learn is to explain. That's why I'm documenting tech concepts with simple analogies (@sreekarreddy.com). AWS Certified β€’ Azure AI Certified β€’ Neo4j Professional β€’ Google Data Analytics When not coding: exploring Sydney, working on side projects, and teaching tech to anyone who'll listen.

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.

More from this blog

esreekarreddy

132 posts