DEV Community

Brijrajsinh parmar
Brijrajsinh parmar

Posted on

4 1

Callback Functions, Explain it to me like I'm 5.

Image description

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.

Image description

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.

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video