The Dark Side of Callbacks in JavaScript

The Dark Side of Callbacks in JavaScript

Introduction

The callback is a very important concept of javaScript which we use in our day-to-day coding, especially in Asynchrouns javaScript system when we need to execute some tasks on completion of some other event. In this blog, we will explore the need for callbacks in JavaScript along with some limitations of using callback functions.

What is a callback?

As the name implies, a callback is a piece of code that will be called back for execution by the javaScript sometimes later.

A callback is a function that is passed as an argument to another function and it is invoked inside the outer function to complete some kind of routine or action.

we all have used setTimeout and setInterval web APIs which take a function as an argument and execute it after a specified time and this function is a callback function.

let's quickly look at an example of a simple callback function

 setTimeout(callBack 10000);
const callBack=()=>{
  console.log("Hii,I am a callBack function passed in a setTimeout")
}

In the above code, the setTimeout takes a callback function and executes it after 10sec.

Need for a callback function

callback functions are generally needed when we have some Asynchronous operation and many more tasks are depends on that operation, for example, suppose we need to create an e-commerce application it has the following functionalities

  • createOrder() API:- This API creates an order for the customer

  • proceedToPayment() API:- This API process payment of a customer.

The above operation proceeds to pay is dependent on creating an order because first the order will be created and then the payment will proceed.

So, to achieve this kind of functionality we can pass the proceedToPayment() API to a createOrder Api via the callback function.

const cart=[
    {id:01,item:"mobile",price:"20000"},
    {id:02,item:"laptop",price:"50000"}
]
//suppose we have API called ceateOrder which creates an Order by taking a cart and takes callback function to call proceedToPayment API
createOrder(cart,function(){
    proceedToPayment(orderId)
})

so, callback functions can be very useful when we have some interdependent operations.

Dark Side of Callbacks

Callbacks have very important use cases in JavaScript but also come with some disadvantages.

There are two major disadvantages of using a callback in javaScript

  • Callback Hell

  • Inversion of Control

Callback Hell

callback hell is a nested callbacks stacked one after the other forming a pyramid-like structure ( called the pyramid of doom) that forms an interdependency between the callbacks and every callback has to depend on the previous callback.

when there are interdependent tasks to perform we generally pass them as a callback to a function and when this process is repeated several times it forms a callback hell

Let's take the same example of an e-commerce app that has now more APIs like

  • CreateOrder

  • ProceedToPayment

  • UpdateWallet

  • ShowOrderSummary

when these APIs are passed inside one another they form callback Hell.

const cart=[
    {id:01,item:"mobile",price:"20000"},
    {id:02,item:"laptop",price:"50000"}
]
//suppose we have API called ceateOrder which creates an Order by taking a cart and takes callback function to call proceedToPayment API
createOrder(cart,function(){
    proceedToPayment(orderId,function(){
            updateWallet(paymentId,function(){
                    showOrderSummary()
            })
    })
})

The above example clearly shows that nested callbacks affect the readability and maintainability of code as code grows horizontally.

Inversion of Control

Inversion of control refers to handling the control of code over to callback in some part of the program.

As we use more nested callbacks inside our code we gradually lose control over the code as we blindly that on completion of some task, our callback function will be executed like in the above example we trust on create order API that it will execute the proceed to payment once it finishes creating order, but what if :

  • createOrder API never calls a callback function that has proceedToPayment API

  • createOrder API calls a callback function that has proceedToPayment API twice.

As mentioned, this scenario can happen if the createOrder API is written by some other Developer and we are not known about the functionality of that API in that case, we lose control over the code.

Summary

  • Callbacks: A callback is a function that is passed as an argument to another function and it is invoked inside the outer function to complete some kind of routine or action.

  • Need for a callback function: A callback is used when there is interdependency between a tasks

  • Disadvantages of callbacks:

    • callback hell: when there are nested callbacks stacked one after the other (forms a pyramid-like structure ) is called a callback hell and it affects the readability and maintainability of code

    • Inversion of Control: It refers to handling the control of code over to callback in some part of the program.

To overcome these disadvantages of callbacks a concept of promise was intoduce,to know more about promise read my next blog Deep Dive into Promises