Callback Functions

Importance and risks of callback functions

Callback Functions

First let us see how the whole process works, JavaScript is a synchronous single threaded language which basically means it can only work on one task at a time and has only one call stack. Within that call stack the JavaScript code is read and gets executed line by line. Then how are we able to achieve asynchronous tasks in JavaScript? This is where callback functions come into the picture.

Callback functions are the functions that are passed to another method as an argument.

Advantage

console.log("I");

setTimeout(function printjs(){
    console.log("JavaScript");
},5000);

console.log("love");

In the above example, function print is a callback function because it has been passed to setTimeout method as an argument. What do you think will be the output for this piece of code?

via GIPHY

The term "JavaScript" logs after 5 seconds.

This is the advantage of a callback function, it helps us change the original nature of the Javascript language and helps us achieve asynchronous tasks in a synchronous single threaded environment.

Disadvantages

Callback hell

Let's have another look at it, for example we want to place an order on an eCommerce website and for that, following steps would have to take place.

  1. Adding items in cart
  2. Placing the order
  3. Proceed to pay
  4. Display order summary
  5. Update wallet

Let's assume these tasks are handled by APIs and we just have to call them.

NOTE : We can't just call these APIs synchronously because updating wallet depends on order summary, which depends on payment and payment depends on cart value

const cart = [item1 , item2 , item3 ]

api.createOrder(cart,function(){
    api.proceedToPay(function(){
        api.orderSummary(function(){
            api.updateWallet()
        })
    })
})

Now, This is what a Callback hell looks like. Callback hell is a situation when callbacks are nested inside other callbacks and it is a major disadvantage because it makes it very hard to maintain and read code.

Inversion Control

In above example, we wrapped api.updateWallet(), api.orderSummary() , api.proceedToPay , inside functions and passed it to api.createOrder. Basically, we gave the control of all APIs in the hands of createOrder API which can prove to be an invitation to a number of risks because the parent API(createOrder()) might have been written by someone else, we don't even know if it is going to make use of the callback we provided it or even misuse the data the callback function holds.

This is how Powerful Callback functions are and that's why they are supposed to be used responsibly