×


Understanding Callbacks and Callback hell in JavaScript : asynchronous behaviour of Javascript Part -1

In most programming languages, functions can accept other function(s) as arguments or return a function. Such functions are called Higher-order functions.
In JavaScript, most APIs and Modules can accept a function as an argument to a function. The functions are called callbacks.

Structure of callbacks

Note that JavaScript functions behave as objects. We can set a function as an object property or store a function into a variable.

JavaScript is a non-blocking programming language. It doesn’t wait or block operation to finish but keeps on executing. For example, consider the case when data is fetched asynchronously, then javascript doesn’t wait for the asynchronous call to get data but keeps executing the next line of code. So in order to do something with the data, we can use callbacks. See the below example in which we use a timeout to wait for the data just like an XHR request which may take some time to complete

Asynchronous callback with  Jquery and a callback function

 

CALLBACK HELL

Consider the above example in which we use a callback function which is passed as an argument to the $.get function in Jquery. Now what happens when we want to send subsequent requests is that the code becomes unreadable and difficult to understand.

We can define callback hell as the situation where callbacks are nested within other callbacks several levels deep, potentially making it difficult to understand and maintain the code. Callback hell is also known as the pyramid of doom.

In later articles, we  will learn more about asynchronous Javascript which will help us avoid problems like callback hell.

5 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *