Member-only story

Javascript Callback functions

Vinodh Thangavel
1 min readDec 9, 2021

--

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. — MDN Web docs

//normal flowconst sum = (a, b) => a + b;console.log(sum(5, 10)) // prints 15

Challenges with asynchronous flow

const sum = (a, b) => setTimeout(() => a + b, 5000);console.log(sum(5, 10)); // prints the timer id not the actual sum

As you can see, when we want to sum it after 5 seconds, we don’t have provision to send it back to caller, as already the value (timer id) is returned to the caller.

Solution- Callback

const sum = (a, b, cb) => setTimeout(() => cb(a + b), 5000);const callbackHandler = (value) => console.log(value);sum(5, 10, callbackHandler); //prints 15 after 5 seconds

Now, we are passing the new function definition to sum function, please note that we should not call the function callbackHandler, we should pass the definition. ie., ̶c̶̶̶a̶̶̶l̶̶̶l̶̶̶b̶̶̶a̶̶̶c̶̶̶k̶̶̶H̶̶̶a̶̶̶n̶̶̶d̶̶̶l̶̶̶e̶̶̶r̶̶̶(̶̶̶)̶̶̶

You can see now, sum function will have the provision to send a value to the called function by calling call back function being sent as the third argument, console.log itself a function call, so we can send console.log function definition as third parameter

const sum = (a, b, cb) => setTimeout(() => cb(a + b), 5000);sum(5, 10, console.log); //prints 15 after 5 seconds

--

--

Vinodh Thangavel
Vinodh Thangavel

Written by Vinodh Thangavel

Passionate lifelong learner, coding enthusiast, and dedicated mentor. My journey in tech is driven by curiosity, creativity, and a love for sharing knowledge.

No responses yet