Callback functions
📞 🔙.in JavaScript are slightly different from normal functions, today in this blog we will understand about the same, how callback functions
actually work.
Callback Functions are those functions that are passed as an argument to another function. And the function in which these are passed is called Higher-Order Function.
What is a callback function?🤔
There is no standard definition of what a callback function
is. But, callback functions are very common in asynchronous programming. We can get to know the JavaScript callback function defined as follows.
A callback function is a function that is:
- passed as an argument to another function
- is invoked inside the outer function to which it is passed as an argument to complete some action, routine, or event.
The outer function in the above reference, to which the callback function
is passed as an argument
, is a function that is actually undertaking the async
task or delegating the same to another nested async function.
Callback functions
are generally triggered after all statements in another function are executed.
As you must have already read Functions are first class Object in JavaScript. This means they can also be used as a constructor.
Need Of Callback Function In JS🧐
We know that JavaScript is a Synchronous Scripting language, which means code runs in a Top-Down
order. But in many cases, the code also runs Asynchronously
.
Actually when we run code asynchronously
using setTimeOut()
or await()
function, then even before that block of code is run, the code beyond that starts executing. Due to this sometimes errors also come in the program or the code does not run according to logic.🤠
For example:
/*define a function to add two numbers*/
function do_sum(num1, num2)
{
var sum = 0;
/*delay execution for 1 second*/
setTimeout(function(){
sum = num1 + num2;
}, 1000);
return sum;
}
var sum = do_sum(10, 20);
document.write(sum);
Output:0
In the example above, a function do_sum()
is created to add 2 numbers
. We assume that the do_sum()
function will take some time to add up the numbers. But the code which takes time to execute inside the function is returning 0
value do_sum()
even before its complete execution.
But by using the Callback Function
, those errors can be avoided😯, because the function for which the callback function
is passed as an argument, the callback functions run only after that function is completely executed.😧
To do the same example using the callback function, we will do something like this -
function do_sum(num1, num2, callback)
{
var sum = 0;
/*delay execution for 1 second*/
setTimeout(function(){
sum = num1 + num2;
/*here call callback function and pass the result*/
callback(sum)
}, 1000);
}
var sum = do_sum(10, 20, function(result){
document.write(result)
});
Output:30
So some use callback functions
in JavaScript like this.
Much the same, in whichever function we pass the callback functions, we get as a parameter in that function, it is called wherever it is needed.
Types of Callback Functions👇
There are two ✌️ types of callback functions:
- Synchronous
- Asynchronous.
Synchronous Callbacks 🔂
Synchronous
means the code statements execute immediately after one another in a sequential manner.
The synchronous callback
is executed during the execution of the higher-order function that uses the callback.
Here the callback
is executing immediately and it is not waiting for any asynchronous operation to finish
. That’s why it is a synchronous callback
.
Synchronous callbacks
are triggered sequentially in another function following the order of operations defined inside another function. Unless the callback execution is completed, they prevent other functions from calling callbacks to complete all its internal logic.
The asynchronous callback🥸
The asynchronous callback is executed after the execution of the higher-order function.
Simply saying😌, the asynchronous
callbacks are non-blocking
: the higher-order function completes its execution without waiting for the callback. The higher-order function makes sure to execute the callback later on a certain event.
In the following example, the later() function is executed with a delay of 2 seconds:
console.log('setTimeout() starts');
setTimeout(function later() {
console.log('later() is called');
}, 2000);
console.log('setTimeout() completed');
// 1. logs 'setTimeout() starts'
// 2. logs 'setTimeout() completed'
// 3. logs 'later() is called' (after 2 seconds)
later()
is an asynchronous callback because setTimeout(later, 2000)
starts and completes its execution, butlater()
is executed after passing 2 seconds. Try the demo.
The asynchronous
way to invoke the callbacks:
- The higher-order function starts execution:
'setTimeout() starts'
- The higher-order function completes its execution:
'setTimeout() completed'
- The callback function executes after 2 seconds:
'later() called'
When to Use a Callback?🤫
Where callbacks really shine is in asynchronous functions, where one function has to wait for another function (like waiting for a file to load).
Callback functions
are very powerful in javascript and it gives us access to a whole asynchronous
world in the synchronous
threaded language.
Key Takeaways:🔐
- When you want one function to execute only after another function has completed its execution, we use
callback functions
in JavaScript. - It needs to pass as a
parameter
to other functions to make a function callback. The function which accepts the callback as a parameter is known as the"High order function".
This article aims to provide an introduction to callback functions
for beginners in JavaScript. I hope the concept of the callback
is clear.
Thanks for reading!🤗🤗