DEV Community

Dharshini E
Dharshini E

Posted on

Javascript - callback & callbackhell

Callbacks in JavaScript?
In JavaScript, callbacks are functions that are passed as arguments from one function to another and are executed after the completion of a certain task. They are commonly used in asynchronous operations, such as reading files, making HTTP requests, or handling user input.

  • A function can accept another function as a parameter.
  • Callbacks allow one function to call another at a later time.
  • A callback function can execute after another function has finished. Example:
function greet(name, callback) {
    console.log(`Hello, ${name}!`);
    callback();  // calling the callback function
}

function afterGreet() {
    console.log('Greeting is complete!');
}

greet('Anjali', afterGreet);

Enter fullscreen mode Exit fullscreen mode

Output:
Hello, Anjali!
Greeting is complete!

What is Callback Hell?
It happens in javascript when you use many nested callbacks(functions passed as arguments to other functions) which makes the code difficult to read and debug. The term "callback hell" describes the deep nesting of functions that can result in poor code readability **and **difficulty in debugging, especially when handling multiple asynchronous operations.
Example:

 setTimeout(() => {
            console.log("Analysis");
        setTimeout(() => {
                console.log("Planing");
                setTimeout(() => {
                    console.log("Design");
                    setTimeout(() => {
                        console.log("Developer");
                            setTimeout(() => {
                            console.log("Testing");
                            setTimeout(() => {
                                console.log("Deployement");

                            },1000);

                        }, 1000);
                    }, 1000);

                }, 1000);
            }, 1000);
        }, 1000);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)