Callback in JavaScript
Understanding JavaScript();
helloooooo JS devs, here I am back with an evergreen topic “Callback functions” in javascript.
as the name suggests it “calls back a function”, you can define it in this way
a function passed as an argument to another function.
The function and another function, arguments, all this sound a bit confusing, right?
you might be thinking I’d have read this on google 😞, why read this?
“ruko jara sabar karo”, let me build up 😅
coding concepts are a practical thing if you don’t see them in action you don’t get them. [at least this is how it works for me and I’m sure there are a lot like me] relax 😎 this is completely normal.
in this story of the callback functions, we will learn what is it, why it is needed, how to use it, and the dark side of it 🌘.
let’s go to the roots of it and understand why callback functions are needed and then we will understand how it works.
what is a callback function?
callback functions are the functions that are passed as an argument to another function, as per the above example printName function is a callback function. callback function gets invoked inside the outer function to complete some chain of actions.
- in the above example of a callback function, printHi is an outer function and we have passed a callback function to it printName.
- you might be thinking we have passed printName but we are calling callbackFunction in printHi what is this? 😕
- to make this clear, we passed printName to printHi we are just referencing the function with the new name callbackFunction for a better understanding that this is a callback function.
Why callback function and how to use it?
- you might be thinking that I can call a function one after the other, and it can do the job, then why callback function is needed?
- the above code snippets give you the same output, then why callback function?
- okay, let me help you remember that the javascript is asynchronous. 🙂
- in javascript the sequence of calling a function matters and not defining it, but if the previously called function does some heavy lifting then javascript doesn’t wait for that function's executions to get completed.
- do you know why Hi got printed after John Doe? Ya exactly you get it correct, printHi function is waiting for 2 seconds to print “Hi” and printName prints the name without waiting.
- you can simply remember one thing, after invoking a function javascript doesn’t wait for the result of the function it continues with another function. “Javascript doesn’t wait for anyone 😜”
- let’s take a real-world example to understand this, assume that we have a chain of tasks to do, and it needs to be done in a sequence so that the output of the first task can be provided as the input of the next in the chain, and you don’t know what task will take what amount of time.
- example: you need to fetch the user data from the database, and based on the user you need to fetch the friends of the user, and based on the friend's data you need to send the Christmas gifts to those friends' addresses [you can send me some gifts as well 🎅 🎁 😅].
- so here comes the callback function in the picture, because we don’t know what time it will take to fetch the users, what if before the users are fetched, the fetch address function gets executed, and what if, before you have the address, send gift functions gets executed, sounds scary 😱 right.
- let's try to solve this using a callback function, to get a better idea of where the callback functions are used.
- sorry for this long snippet 😩 but it is very helpful to understand why callback functions are used.
- getUser is a function that fetches a user from the database, but we don’t know what time it will take to get the user, and the same for getUserFriendsDetails and sendGifts, so once the user data is fetched from the database it gets returned into a callback function.
- the user data is fed to the function getUserFriendsDetails and the user's friends' details are fetched from the DB and sent back in a callback function.
- user friends' details are fed to sendGifts as we need to send gifts to the user's friends and we can get friends to address from it, at the end, the last callback function is called to confirm all the gifts are sent to the friends.
- now let’s assume that you call each function separately in a sequence there is no guarantee of getting the execution completed in a sequence because we don’t know what time it will take to complete the previous task and we are completely dependent on the output of the previous function.
- callback functions can provide you with better control over the sequence of execution of functions.
some dark sides of the callback functions
- code becomes less readable and unmaintainable, as you can see in the above looonnggg snippet.
- code grows horizontally instead of growing vertically.
- there can be N number of nested functions in a massive application with a huge codebase, the above code structure is known as the pyramid of doom in programming, and this is known as callback hell.
- inversion of control is also a big problem with callbacks, you lose control over the code.
- you have control over the sequence of execution of functions but what if the function doesn’t return anything, or it breaks in between, or if the callback is executed twice, or if the callback is never called, there are N number of possibilities you don’t have control over?
whats the solutions to the above problems?
- promises, yes to solve the above issues you can use promises, here's a small story on promises give it a read.