Callbacks in Javascript

Callbacks in Javascript

ยท

3 min read

In this article we'll learn about callback, its uses as well as issues, but before diving deep into callback let us understand about function which is the base of callback and it'll help us to understand callback better.

What's function?

A function is a block of code that performs a certain defined task when called. function in js treated as a first-class-citizen & it has different implications like -

  • functions are objects.
  • functions can be assigned to a variable.
  • functions can be passed as a parameter to a function.

For example -

// function declaration
function greetUser(name) {
    console.log(`Hi, ${name}. You're welcome.`); //block of code
}
//calling `greetUser` function
greetUser('Anand'); // Hi, Anand. You're welcome.

Now, since we learnt about function, lets go further and learn about callback.

What Are Callback Functions?

Callback functions are those functions which are passed as a parameter to other functions.

For example -

//  function declaration
function greetUser(name, callbackFn) {
    console.log(`Hi, ${name}. You're welcome.`); //block of code
    callbackFn(); //calling another func which was passed as an argument
}

// callback function
function callMeBack() {
    console.log('I was called from greetUser()');
}

// passing function as an argument
greet('Anand', callMeBack);

Issue with callbacks

There are few callback issues

  1. Callback hell
  2. Inversion of control

What is callback hell?

Asynchronous operation in JS can be achieved through callbacks. whenever there are multiple dependent asynchronous operation it'll result in a lot of nested callbacks. this will cause a pyramid of dom like structure. it'll start growing horizontally rather than vertically and thus code readability decreases and hence unmaintainable.

Example, callback looks like this -

//array of products to be bought
const cart = ["shoe", "pants", "kurta"];
//create order for given cart
api.createOrder(cart, function(){
    //once order created, proceed for payment
    api.proceedToPayment(function(){
        //once payment completed, show order summary
        api.showOrderSummary(function(){
            //you may want to update wallet
            api.updateWallet();
        })
    });
});

so above example is self explanatory, like if a customer wants to buy array of products we need to create order first and if order is created successfully. We need to charge for those bought products, hence we proceed further for payment and so on. But here we can see how codes are growing horizontally because of multiple nested callbacks and this is called callback hell.

Inversion of control (IOC)

When we give the control of callbacks being called to some other API, is called IOC. this may create a lot of issues like that API may be buggy & may not call our callback or even call our callback twice.

In layman's terms IOC means loosing the control over your code due to overuse of (nested) callbacks.

for example -

//array of products to be bought
const cart = ["shoe", "pants", "kurta"];
//create order for given cart
api.createOrder(cart, function(){
    //once order created, proceed for payment
    api.proceedToPayment(function(){
        //once payment completed, show order summary
        api.showOrderSummary(function(){
            //you may want to update wallet
            api.updateWallet();
        })
    });
});

here we are creating order for given cart and passing proceedToPayment() as a callback function which will be called once order is created successfully...but here we don't have control over createOrder() api and we are not sure whether it'll create order successfully or not and even possible that it may create order twice ie. anything can happen...but again as we can see we are completely dependent on it for further action like proceedToPayment() & this may create issue by breaking the flow of program & may result as bad experience for a customer.

Thank You for reading :)

Happy Learning & Coding :)

ย