Skip to main content

Command Palette

Search for a command to run...

Callback Power: The Secret Behind JavaScript’s Asynchronous Magic

Callback Power: The Secret Behind JavaScript’s Asynchronous Magic

Updated
2 min read
Callback Power: The Secret Behind JavaScript’s Asynchronous Magic

A callback function is a function that passes an argument to another function and execute later.

This mechanism is a JavaScript event driven asynchronous programming model.

Here is an example


function welcome(name, callbackFunction) {
    console.log("Hello ", name);
    callbackFunction();
}

function message() {
    console.log("Welcome to onboard!!");
}

welcome("John", message);

The output will become

Hello  John
Welcome to onboard!!

Here we can clearly see we pass a function reference of message to the function welcome and inside the welcome function we just call it.

Why we use it ?

Callback functions mostly used in

  • API Request on fetching data

  • Database query

  • event listener in DOM

  • When a function needs to behave differently based on input then we use callbacks

  • JavaScript is event driven and in event listeners callback used mostly

document.getElementById('btn').addEventListener("click", function () {
    console.log("User clicked the button");
})

When to use it

  • Handling API response

  • Handling asynchronous tasks

  • Implement event driven programming

  • To create higher order function

When not to use it?

Callback Hell

When the code becomes nested and unreadable then we should avoid to use callbacks. This phenomena is called callback hell. It creates unreadable, unmaintainable code with fragile error handling and complex debugging, resulting from deep, nested asynchronous operations.

It makes code hard to follow due to excessive indentation and prevents efficient parallel execution, forcing strict serial processing.

It makes the code

  • Poor Readable

  • Difficult to Maintenance

  • Makes error handling complex

  • Make debugging more difficult.

Here is an example code

// Example of Callback Hell
getData(function(a) {
    getMoreData(a, function(b) {
        getEvenMoreData(b, function(c) {
            getFinalData(c, function(d) {
                console.log(d);
            });
        });
    });
});

Final Thoughts

Callbacks are very important part of the JavaScript but when the code become nested it creates a callback hell, which makes the code

  • poor readable

  • difficult to manage and debug

Another way is to use Promises in JavaScript to avoid all the problems with callbacks.

Reference Article

You can follow the following articles for more understanding

That's it, now you understand Callbacks in JavaScript. I’d love to hear your thoughts and feedbacks.

Thank You for your patients. ❤️