×

Callback and Callback Hell in JavaScript

The widely used client-side programming language JavaScript is simple, light, and interpretive. JavaScript is used by the majority of client-side web applications. It is also possible to use JavaScript on the server side because it comes with a runtime environment (Node.js). Callbacks and callback hell are two topics we'll talk about in this article. Start with JavaScript's synchronous and asynchronous implementations to understand what the callback hell is. The result is returned as soon as the browser is able to in Synchronous JavaScript when the code is executed. Because it is single-threaded, only one operation can take place at once. Therefore, while an operation is running, all other processes are suspended. AJAX is necessary for several JavaScript functions because their responses aren't always immediate. It takes some time. Therefore the subsequent operation cannot begin right away. It must wait for the background function to complete. The callbacks must be asynchronous in these situations. A callback is a function that is supplied as an argument to a different function, which, depending on the outcome, will then execute the callback. Carry on reading to understand more about this.

What is a callback?

Callbacks are an excellent approach to address something once another task has been done. Here, "something" refers to the execution of a function. Callbacks can be utilised if we wish to run a function immediately following the return of another function. Callbacks are generally utilised when managing asynchronous processes, such as registering event listeners, sending an API request to Google Maps, retrieving/writing data from/into a file, and other related tasks. Callbacks are used in all of the aforementioned operations. In this manner, the callbacks are utilised to handle the data or error from the asynchronous action once it is returned to our code.

See the following code to understand more about the callback.

Example 1:

function addition(a, b , callback){
console.log(`The sum of ${a} and ${b} is ${a+b}.`);
callback();
}
function display(){
console.log('This must be printed after addition');
}
	
addition(2,3,display);	

Output:

Callback and Callback Hell in JavaScript

Explanation:

The two functions are display and addition (a, b, callback) (). The display() method is called with the addition() function, which is provided as the third parameter to the add function along with two numbers. As a result, the callback display(), along with arguments 1, 2, and addition(), is executed. The callback function is activated as soon as the addition of the two numbers is printed by addition(). Therefore, whatever is contained in the display() appears as the output.

Example 2:

function sub(a, b , callback){
console.log(`The subtraction of ${a} and ${b} is ${a-b}.` );
callback();
}
sub(5,6,function display(){
console.log('This must be printed after subtraction.');
});

Output:

Callback and Callback Hell in JavaScript

Example 3:

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

Output:

Callback and Callback Hell in JavaScript

Explanation:

To simulate certain I/O operations or a request call, setTimeout has been utilised in the mainFunction in this case. The callback function that was supplied is utilised to add up the array's elements. The array's sum, which is nine, is printed after two seconds.

What is callback hell?

This is a significant problem brought on by complicated callback nesting in the code. Every callback in this situation accepts an argument that is the outcome of earlier callbacks. The code structure resembles a pyramid in this way, making it challenging to comprehend and maintain. Additionally, if one function has a bug, it affects the entire system.

How to handle callback hell?

  1. Any asynchronous function will return an object called a promise, to which callback methods can be added depending on the output of the prior function.
  2. As a result, these promises are added to the event queue so that they won't obstruct running JS code. The event queue also completes its tasks once the results are returned.
  3. JavaScript offers a simple way out of callback hell. The event queue and promises are used for this.
  4. Promises can invoke async callbacks using the. then() method. The order is likewise rigidly maintained, and we are free to chain as many callbacks as we like.
  5. The. fetch() method is used by promises to retrieve objects from the network. When a block fails, it also employs the. catch() method to handle any exceptions.

Related Topics

Design a BMI calculator using JavaScript

BMI calculator BMI stands for Body Mass Indicator. It is a numeric value which is calculated based on the height and weight of a person. It represents the fatness of the...

4 minutes read.

JavaScript focus on input

In JavaScript, the elements can be focused using either focus() method or onfocus() event. What is focus() method? When we want to focus on an element (if it can be focused) or...

4 minutes read.

Javascript Re-Password Validation

Example <!DOCTYPE html>   <html>   <head>   <script>   function pass_validation()   {   var firstpassword=document.f1.password1.value;     var secondpassword=document.f1.password2.value;     if(firstpassword==secondpassword){     return true;     }     else{   alert("Password does Not Match");     return false;     }     }    </script>   </head>   <body>   <form name="f1" action="/JavaScript/Index" onsubmit="return pass_validation()">   Password:<input type="password" name="password1" /><br/>   Re-enter :<input type="password" name="password2"/><br/>   <input type="submit">   </form>   </body>   </html> Try Now ← Prev Next → ...

1 minute read.

Javascript String

String object works with series of characters. It is used to store and manipulate text. There are two ways to create string in JavaScript: String literal. Using new keyword. String literal By using double quotes...

4 minutes read.

Javascript comment

Introduction In programming languages, comments are a method to include meaningful annotations within the code that the compiler or interpreter will ignore at run time. That is to say, though comments...

7 minutes read.

Javascript loops

Loops in JavaScript: Loops are used to execute a specific piece or block of code repeatedly until the given condition is satisfied. What is a Loop? Almost all loops contain a certain...

7 minutes read.

Javascript Variable

Variables are used to store values (name="Ram") or expressions (Sum=x+y). Before using of variable first we need to declare it. We use keyword var to declare a variable like this: var name; There are two types of variables: Local Variable ...

1 minute read.

Javascript Window Object

The window object represents a window in browser. An object of window is created automatically by the browser. Window is the object of browser, it is not the object of JavaScript. The...

3 minutes read.

JavaScript Time Picker Demo

Time Pickers in JavaScript are lightweight and mobile-friendly controls that let the users enter or select date and time values. These values can be from a pop-up calendar or a...

5 minutes read.

Javascript Tutorial

JavaScript is a light-weight, dynamic scripting language that is mainly employed to create interactive front-end web applications. It was originally developed in 1995 by Brendan Eich at Netscape Communications Corporation...

5 minutes read.

Javascript Switch Statement

Introduction Conditional statements are simple building blocks in programming languages and are utilized fairly frequently. This portion of Developing Conditional Statements in JavaScript talks about how to utilize the if, else,...

5 minutes read.

Javascript Cookies

Cookie is a piece of data which is sent from a website and stored locally by the user's browser. Cookie is needed because HTTP is stateless protocol. Today most of...

1 minute read.

Javascript Email Validation

We can validate the email with the help of JavaScript. Here we check the condition related to any email id, like email it must have "@" and "." sign and...

2 minutes read.

Javascript Print

JavaScript help's the functionality using the print function of window object. In JavaScript print function window.print() print the current web page when it executed. We can call function directly using onclick...

1 minute read.

Javascript Password Validation

Here we see that how to validate any password field. Like password field can be blank and length of password is minimum 8 characters. Example <!DOCTYPE html>   <html>   <head>   <script>   functionpass_validation()   {     var password=document.myform.password.value;     if (password==null || password=="")   {     alert("password can't be blank");     return false;     }   else if(password.length<8)   {     alert("Password must be at least 8 characters long.");     return false;       }     }     </script>   </head>   <body>   <form name="myform" method="post" action="register.php" onsubmit="return pass_validation()" >   Password: <input type="password" name="password">   <input type="submit" value="submit">   </form>   </body>   </html> Try Now ← Prev Next → ...

1 minute read.

Javascript Number

The Number object is a wrapper object which allows you to work with numerical values. The number object is created using the Number() constructor.It may be integer or floating-point. Syntax var n=new Number(value); Examples <!DOCTYPE html>   <html>   <body>   <script>   var x=100;//integer value   var y=100.7;//floating point value   var z=12e5;//exponent value, output: 1200000   var n=new Number(20);//integer value by number object     document.write(x+" "+y+" "+z+" "+n);   </script>   </body>   </html> Try Now Output 100 100.7 1200000 20 Description The primary...

1 minute read.

JavaScript p5.js

Introduction to p5.js P5.js is a JavaScript library for creative programming. It is built on Processing, a coding environment for creativity. Processing's major goal is to make it as simple as...

4 minutes read.

D3.js Tutorial

Introduction of D3.js D3.js is referred to as a JavaScript library that is used to manipulate the documents according to the data. The intensity of D3 is based on web standards...

5 minutes read.

Synchronous and Asynchronous in JavaScript

JavaScript is a powerful and versatile language that is used all over the web, from small websites to large applications. It is essential for developers to understand the differences between...

9 minutes read.

Javascript Object

An object is an entity having state and behavior. JavaScript is an object oriented scripting language. JavaScript is template based not class based but we can create object directly. Syntax to...

2 minutes read.