DEV Community

Cover image for Understanding JavaScript Callbacks: The "Don't Call Us, We'll Call You" Concept
DHANRAJ S
DHANRAJ S

Posted on

Understanding JavaScript Callbacks: The "Don't Call Us, We'll Call You" Concept

Imagine you are at a busy restaurant. You place your order, but instead of standing at the counter waiting for your food, the waiter gives you a buzzer. You go sit down, chat with friends, or check your phone. When the food is ready, the buzzer goes off.

In JavaScript, a Callback Function is exactly like that buzzer.

1. What is a Callback Function?
In simple terms, a callback is a function passed as an argument to another function.

2. Why do we use it?
JavaScript usually runs code line-by-line. But some things (like loading a large image or fetching data) take time. Callbacks prevent the whole website from "freezing" while waiting for that task to finish.

3. A Simple Example
Let’s look at a basic example where we pass a greeting function into another function.

// The Callback Function
function sayGoodbye() {
    console.log("Goodbye! Task is finished.");
}

// The Main Function
function processUser(callback) {
    console.log("Processing user data...");
    // Simulating a task, then calling the callback
    callback(); 
}

// Passing sayGoodbye as an argument
processUser(sayGoodbye);
Enter fullscreen mode Exit fullscreen mode

output

  1. Chef is cooking...
  2. Your food is ready

What happened here?

  1. processUser starts running.
  2. It prints "Processing user data..."
  3. It then executes callback(), which is actually the sayGoodbye function we passed in.

4. Practical Use: setTimeout
The most common way beginners see callbacks is with timers.

console.log("Start");

setTimeout(function() {
    console.log("This happens after 3 seconds!");
}, 3000);

console.log("End");
Enter fullscreen mode Exit fullscreen mode

The Result:

  • "Start" is printed.
  • "End" is printed.
  • 3 seconds later, the callback function inside setTimeout runs and prints "This happens after 3 seconds!"

Here, the anonymous function inside is the callback. It waits for the 3-second "long task" to finish before running.

5. 3 Golden Rules

  • A callback is just a function.
  • Pass the name, don't call it: Pass myFunc, not myFunc().
  • Async Power: They are the secret behind why websites can do many things at once.

6. summary

Top comments (0)