×

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

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.

What is Ternary Operator in JavaScript?

In some cases, a ternary operator can be used instead of an if-else expression. A ternary operator examines a condition and then runs a block of code in response to...

4 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 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 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 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 Event

Events are things that happen, usually user action, that are associated with an object. All object have properties and methods. Some objects also have events. The event handler is a command that is...

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 radio button checked value

What are radio buttons? A radio button is defined as an icon that is used to take input from the user. The user can choose only one option(value) from the group...

5 minutes read.

Javascript Date

In JavaScript Date Object is data type build into the JavaScript language. Data object are created with the new Date(). JavaScript Date instance that represents a single moment in time. JavaScript...

2 minutes read.

Javascript Math

Math is build-in object that has properties and methods for mathematical constants and functions. It allows you to perform mathematical tasks on numbers. Syntax varpi_val = Math.PI; varsin_val = Math.sin(30); Examples Math.pow() Math.pow(x,y) returns the value of x to the power...

2 minutes 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 Redirect Button

What is a redirect button? When a button acts as a hyperlink, it is known as a redirect button. On clicking the button, it transfers the user to another page. How to...

3 minutes read.

Javascript Find Object In Array

What is find() method? It returns the value of the first element in the given array that fulfils the given testing function. However, if no values from the array are able...

3 minutes read.

JavaScript setTimeout()

The setTimeout() method creates a timer that, when it expires, runs a function or provides a piece of code. setTimeout() is an asynchronous function, which means that it will not interrupt...

3 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 Dialog Box

A JavaScript dialog box is predefined function which is used to perform different task. Some functions are used in JavaScript Dialog box. FunctionDescriptionalert()To give alert message to userprompt()To input value from...

2 minutes read.

Javascript Page Redirect

The window.location object can be used to get the current page address (URL) and to redirect browser to new page. In some websites when we visit, we face a situation where we...

3 minutes read.

Minify JavaScript

What do you mean by the term ‘Minification’? The technique of minification reduces the amount of code and markup in your websites and scripting files. It's one of the most used...

4 minutes 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.