How to Use Callback Functions in JavaScript?

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 which are passed as an arguments to another function. And the function in which these are passed is called Higher – Order Function.

As you must have already read that Functions are first class Object in JavaScript. Means, they can also be used as a constructor.

Need Of Callback Function In JS

We know that JavaScript is Synchronous Scripting language, means code runs in 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 which sometimes errors also come in the program or the code does not run according to logic.

For example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> JavaScript Callback Function </title>
</head>
<body>
<script type="text/javascript">
/*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);
</script>
</body>
</html>

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-

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> JavaScript Callback Function </title>
</head>
<body>
<script type="text/javascript">
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)
});
</script>
</body>
</html>

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.