DEV Community

Cover image for JavaScript Callbacks Explained Easily ☕
Burhanuddin S. Tinwala
Burhanuddin S. Tinwala

Posted on

JavaScript Callbacks Explained Easily ☕

JavaScript callbacks are like the backbone of asynchronous programming. But what are they exactly? 🤔

A callback function is a function passed as an argument to another function, which is then executed later, usually after some operation completes.


Why Callbacks Matter

JavaScript is single-threaded, meaning it can only handle one task at a time. Callbacks allow you to manage time-consuming tasks (like waiting for data) without blocking the rest of your code.

Think of callbacks as a way to say, “When this is done, let me know, and I’ll do something with it.”


Callback Example: Making Coffee ☕

Let’s bring callbacks to life with a relatable example—making coffee! While the coffee brews, you might toast some bread or scroll on your phone. When the coffee is ready, you’re notified to pour and enjoy it.

Here’s how this looks in JavaScript:

// Function to simulate brewing coffee
function brewCoffee(callback) {
    console.log("Brewing coffee...");

    // Simulate a delay for coffee brewing
    setTimeout(() => {
        console.log("Coffee is ready!");
        callback(); // Notify when coffee is ready
    }, 2000); // Simulated 2-second delay
}

// Callback function to pour and drink the coffee
function drinkCoffee() {
    console.log("Pouring coffee into the cup and enjoying it ☕");
}

// Start brewing coffee and pass drinkCoffee as the callback
brewCoffee(drinkCoffee);

console.log("While the coffee brews, I'll toast some bread...");
Enter fullscreen mode Exit fullscreen mode

What’s Happening Here?

1️⃣ brewCoffee Function: Starts the coffee-making process and accepts a callback function to execute later.

2️⃣ setTimeout: Simulates the time it takes to brew coffee (2 seconds).

3️⃣ drinkCoffee Function: The callback that gets executed once the coffee is ready.

4️⃣ Non-Blocking Behaviour: The app continues running other tasks (e.g., toasting bread) while the coffee brews.


Why Learn Callbacks?

Callbacks are essential for handling asynchronous tasks in JavaScript, like:

  • Fetching data from an API
  • Handling user events (e.g., button clicks)
  • Managing timers and intervals

By mastering callbacks, you’ll gain the skills to handle asynchronous programming like a pro!


💬 Can You Guess the Output?

Drop your guesses in the comments, and I’ll reveal the correct answer! Let’s see who gets it right.

Let's Connect LinkedIn

Top comments (2)

Collapse
 
randalschwartz profile image
Randal L. Schwartz

Promises disentangle callbacks, and should probably be preferred for modern APIs.

Collapse
 
bst53 profile image
Burhanuddin S. Tinwala

Absolutely, promises make asynchronous code so much cleaner!