The Wayback Machine - https://web.archive.org/web/20240630074256/https://www.geeksforgeeks.org/what-to-understand-callback-and-callback-hell-in-javascript/
Open In App

What to understand Callback and Callback hell in JavaScript ?

Last Updated : 08 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

JavaScript, a single-threaded language, relies on callbacks for handling asynchronous tasks. Callbacks execute code once an operation finishes. But as the code complexity increases, the risk of callback hell emerges.

Callback:

A callback is a function that is passed as an argument to another function that executes the callback based on the result. They are basically functions that are executed only after a result is produced. Callbacks are an important part of asynchronous JavaScript.

Example: In this example, we have used setTimeout in the mainFunction to mimic some I/O Operations or a request call. The callback function passed is used to sum up the elements of the array. After 2 seconds have passed, the sum of the array is printed which is 9.

Javascript




// Main function
const mainFunction = (callback) => {
    setTimeout(() => {
        callback([2, 3, 4]);
    }, 2000)
}
 
// Add function
const add = (array) => {
    let sum = 0;
    for(let i of array) {
        sum += i;
    }
    console.log(sum);
}
 
// Calling main function
mainFunction(add);


Output:

9

Callback Hell:

Callback Hell is essentially nested callbacks stacked below one another forming a pyramid structure. Every callback depends/waits for the previous callback, thereby making a pyramid structure that affects the readability and maintainability of the code. 

Example: In the below example we have split the word GeeksForGeeks into three separate words and are trying to animate each word after one after another.

HTML




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible"
          content="IE=edge">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">
 
    <title>Callback Hell</title>
     
    <style>
        * {
            padding: none;
            margin: none;
            box-sizing: border-box;
        }
 
        .word {
            color: #308d46;
            font-size: 4rem;
            transition: all .5s ease-in;
            margin: 0 5px;
            transform: translateY(3.8rem);
            opacity: 0;
        }
 
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            width: 95vw;
            height: 95vh;
        }
 
        .container {
            overflow: hidden;
            display: flex;
            flex-direction: row;
        }
 
        .animate {
            opacity: 1;
            transform: translateY(0);
        }
    </style>
</head>
 
<body>
    <div class="container">
        <h2 class="word">Geeks</h2>
        <h2 class="word">For</h2>
        <h2 class="word">Geeks</h2>
    </div>
</body>
<script>
    let words = document.querySelectorAll(".word");
 
    const animateAll = (animate) => {
        setTimeout(() => {
            animate(words[0]);
            setTimeout(() => {
                animate(words[1]);
                setTimeout(() => {
                    animate(words[2]);
                }, 1000)
            }, 1000)
        }, 1000)
    }
 
    const animate = (word) => {
        word.classList.add("animate");
    }
 
    animateAll(animate);
</script>
</html>


Output: We can notice that the animateAll function takes a pyramid structure, thereby making it difficult to read.

Geeks For Geeks animated callback output

Reference: https://developer.mozilla.org/en-US/docs/Glossary/Callback_function



Similar Reads

What is Callback Hell in JavaScript ?
Callback hell is also known as the "pyramid of doom,". This situation of callback hell is created when there are multiple nested callback functions are there which make the code complex and hard to read. This occurs mainly in the asynchronous programming environment like while handling async requests or file operations where the function doesn't ex
1 min read
What is Callback Hell and how to avoid it in Node.js ?
In this article, we will learn about Callback Hell and how can it be avoided. Callbacks Hell is the situation in which we have complex nested callbacks. As we have mentioned the term "Callback" so Before diving into Callback Hell details, let’s know a little about what Callback is. A Callback is a function that is called automatically when a partic
4 min read
What is callback hell in Node.js ?
To know what is callback hell, we have to start with Synchronous and Asynchronous Javascript. What is Synchronous Javascript? In Synchronous Javascript, when we run the code, the result is returned as soon as the browser can do. Only one operation can happen at a time because it is single-threaded. So, all other processes are put on hold while an o
4 min read
How to Avoid Callback Hell in Node.js ?
Callback hell, often referred to as "Pyramid of Doom," occurs in Node.js when multiple nested callbacks lead to code that is hard to read, maintain, and debug. This situation arises when each asynchronous operation depends on the completion of the previous one, resulting in deeply nested callback functions. Fortunately, modern JavaScript and Node.j
3 min read
How to escape try/catch hell in JavaScript ?
In this article, we will try to understand how we may escape from multiple try/catch hell (that is multiple sequences of occurrences of try/catch blocks) in JavaScript. Let us first quickly visualize how we may create a try/catch block in JavaScript using the following illustrated syntax: Syntax: Following is the simple syntax that we may use to cr
4 min read
What is the Difference between Returning a Callback and Just Calling a callback ?
In Node.js, callbacks are a fundamental part of asynchronous programming. Calling a callback is immediate and direct, while returning a callback defers execution and gives control to the caller. They are functions passed as arguments to other functions and are typically called once an operation completes. Understanding the nuances between returning
5 min read
How to understand WeakMap in JavaScript ?
The WeakMap object stores key/value pairs. The keys should be objects, and also the value may be anything. In JavaScript, a map API may be engineered with 2 arrays, one for keys and one for values that are shared by the four API functions. Setting parts on this map would entail at the same time inserting a key and value onto the top of every one of
3 min read
How to Understand Recursion in JavaScript ?
In this article, we will understand the basic details which are associated with the understanding part as well as the implementation part of Recursion in JavaScript. Let us first understand what exactly is Recursion. Recursion: We could define recursion formally in simple words, that is, function calling itself again and again until it doesn't have
3 min read
What to understand the Generator function in JavaScript ?
Generators generate value on the fly which means whenever there is a need for that value then only it will be generated. It means the value is generated but not stored in memory so it takes less time to execute. It uses asterick (*) symbol after the keyword function i.e. function* to tell javaScript it is a generator function. The generator functio
4 min read
How to understand various snippets of setTimeout() function in JavaScript ?
When dealing with JavaScript, there will be times when you wish to run a function after a particular period of time. For this, we use setTimeout(), an asynchronous method that sets a timer, which then executes the function or specified piece of code once the timer expires. In this article, we will be exploring several code snippets on how setTimeou
3 min read
three90RightbarBannerImg