28
Callback Functions, Explain it to me like I'm 5.
Hi, since a 5yo will like chocolates, I will use that as an example!
Assume you are the 5yo kid, and I give you a chocolate. If you open the wrapper and pop the chocolate into your mouth right away, that is a normal function. On the other hand, if you give it to your mom and she, say, after 5 minutes unwarps the chocolate and pops it into your mouth, voila! you have a callback function.
In programming, if all the data required by a function is ready, we can right away call that function ourselves, as below:
function greet(name) {
console.log("Hi, " + name )
}
greet("Brij")
On the other hand, assume we should fetch the name from a database over the network, which will take some time — known as an asynchronous operation, and in such a case, if we call the greet()
function ourselves, name will still be undefined and our code will not work as intended. In such cases, we pass the greet()
function itself as an argument to another function, say, fetchName()
, that will first do the fetching and then using the fetched data call the greet()
function, as below:
function fetchName(cb) {
const name = // code to get the name
cb(name)
}
fetchName(greet)
Note that here we are not calling the greet()
function; rather, the fetchName()
function will call it! In other words, we are passing a function as an argument to another function to be called back later by that function.
I hope the above drops the penny further!
if you enjoyed this do consider to drop a like or a follow.
28