Saad Baig

Saad Baig

typing-shape

What are Callbacks in JavaScript? A Simple Guide

javascript

July. 13. 2023

Call Back Photo by Axel Grollemund

A callback in JavaScript refers to a function that is passed as an argument to another function and is invoked or called at a later point in time.

In other words, it's a way of providing a function to be executed as a response to an event or as a completion of a task.

Callbacks are commonly used in asynchronous programming, where a function needs to wait for an asynchronous operation to complete before proceeding with its execution. Instead of blocking the execution, a callback function is passed to the asynchronous function. When the operation is finished, the callback is invoked, allowing the program to continue.

A Simple Analogy

Imagine you're having a dinner party at your house. You want to prepare a delicious meal for your guests, but you also have other things to do, like setting the table, decorating the house, and welcoming your friends.

In this scenario:

  • You (the main program) are responsible for organizing the party and overseeing everything.
  • The tasks you need to complete (setting the table, decorating, etc.) are like the steps in your program that need to be executed.
  • However, cooking the main course requires some time, so you assign it to a professional chef (an asynchronous operation) who will take care of preparing the dish.

Here's where the callback comes in:

  • You provide the chef with instructions (the callback function) on what to do once the dish is ready. For example, you might ask the chef to notify you when the main course is cooked.
  • While the chef is busy cooking, you can continue with other tasks, like setting the table or welcoming your guests.
  • When the chef finishes cooking, they call you back (invoke the callback function) to let you know that the main course is ready.
  • Upon receiving the callback, you can pause your current task, and then you shift your attention to serve the main course to your guests.

So, In the above analogy, you (the main program) assign the cooking task to the chef (asynchronous operation) and provide a callback function (instructions) to be called back once the dish is ready.

Meanwhile, you can continue doing other things. When the chef finishes cooking, they invoke the callback function, allowing you to handle the cooked dish accordingly.

Code Example

Let's look at an example that demonstrates an asynchronous callback in JavaScript using the setTimeout function:

function fetchData(callback) {
  // Simulating asynchronous operation
  setTimeout(function() {
    const data = { name: 'Jack', age: 23 };
    callback(data);
  }, 2000);
}

function displayData(data) {
  console.log(data);
}

fetchData(displayData);
console.log('Fetching data...');

In this example, we have the fetchData function that simulates an asynchronous operation, such as fetching data from a server. It takes a callback function as an argument. Inside fetchData, we use setTimeout to introduce a delay of 2000 milliseconds (2 seconds) to simulate the asynchronous behavior.

After the timeout elapses, we create a data object and invoke the callback function, passing the data as an argument.

The displayData function serves as the callback. It receives the data as a parameter and simply logs it to the console.

Finally, we call fetchData(displayData) to initiate the asynchronous operation. We also log a message 'Fetching data...' immediately after to show that the program doesn't wait for the callback to complete.

The output will be something like this:

Fetching data...
{ name: 'Jack', age: 23 }

As you can see, the callback function displayData is invoked after the asynchronous operation (the setTimeout) finishes. This allows us to handle the fetched data asynchronously and perform actions based on that data when it becomes available.

Wrapping Up

Callbacks are powerful because they allow us to write asynchronous code that can respond to events or handle the results of asynchronous operations. They provide a way to control the flow of execution in situations where the order of operations is not guaranteed.

However, as JavaScript has evolved, there are now other alternatives to callbacks, such as Promises and async/await, which provide more readable and structured ways to handle asynchronous operations. I'm excited to delve into these topics soon.

Saad Baig

saad-baig

Full Stack Developer. I build everything from small business sites to rich interactive web applications.

twitter
github
linkedin