Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What is a callback in JavaScript

Understanding Callbacks

Let's start with a simple analogy. Imagine you're at a restaurant, and you just ordered your meal. Instead of making you wait at the counter, the staff gives you a buzzer and tells you it will buzz when your order is ready. You're free to go sit, chat or do anything else. When the buzzer buzzes, you know your order is ready. This buzzer is similar to what we call a callback in JavaScript.

What is a Callback?

In JavaScript, a callback is a function that is passed as an argument to another function and is executed after its parent function has completed. In our restaurant analogy, the callback is the buzzer.

In technical terms, JavaScript is an asynchronous language, meaning it can perform non-blocking operations. This means JavaScript doesn't have to wait for an operation to complete before moving on to the next one. It can move on and complete other operations, and come back when the results are ready.

Code Example of a Callback

Let's have a look at a simple example of a callback function:

function greet(name, callback) {
    console.log('Hello ' + name);
    callback();
}

// calling the function
greet('John', function() {
    console.log('This is a callback function');
});

In the above example, the greet function takes two arguments, a string and a callback function. First, it logs a greeting message to the console, and then it calls the callback function.

The output of the code will be:

Hello John
This is a callback function

Callbacks and Asynchronous Programming

Callbacks are widely used in asynchronous programming. Asynchronous programming is a design pattern which ensures the non-blocking code execution. Non-blocking means that if a function is set with a task that takes some time to execute, JavaScript doesn't wait for that function to finish. Instead, it will execute the rest of the code and then come back to the task when it's done.

Here is an example of asynchronous programming using callbacks:

function downloadImage(url, callback) {
    setTimeout(() => {
        // let's assume it takes 3 seconds to download the image
        console.log(`Downloaded image from URL: ${url}`);
        callback();
    }, 3000);
}

console.log('Start downloading image...');
downloadImage('http://example.com/image.png', function() {
    console.log('Finished downloading image');
});
console.log('Doing other stuff...');

The output will be:

Start downloading image...
Doing other stuff...
Downloaded image from URL: http://example.com/image.png
Finished downloading image

Even though we called the downloadImage function before console.log('Doing other stuff...');, the latter gets executed first. That's because JavaScript doesn't wait for the image download to complete. It moves on to the next line of code, and once the image has finished downloading, the callback function is executed.

Conclusion

Callbacks are like the secret ingredient in a recipe that makes your dish stand out. They are at the heart of JavaScript's power, enabling you to write efficient, non-blocking code. They may seem a bit daunting at first, but once you get the hang of them, you'll realize their brilliance.

Just like the buzzer in a busy restaurant allows you to enjoy your wait without constantly checking on your order, callbacks allow JavaScript to efficiently multitask, making the most of its asynchronous capabilities. So the next time you're working with JavaScript, remember the little buzzer, and put callbacks to work!