Friday, October 14, 2022
JavaScript runs code sequentially in top-down order. But Wait!, have you ever been to the situation where you need to run a function only after another function has run successfully. Like this condition below:
function add(a, b) {
setTimeout(() => {
const sum = a + b;
return sum;
}, 2000);
}
function display(value) {
console.log(value);
}
let result = add(10, 5);
display(result);
Output:
undefined
In this scenario we expect the output to be 15, but we get undefined.
Let's analyze what is going on here.
Problem
To resolve the situations like above, the approach of Callback Function is used.
A callback function is simply a function that you pass into another function as an argument for later execution.
This technique allows a function to call another function.
Syntax:
function functionA() {
// Some codes
}
function functionB(callbackFunction) {
// Some codes
callbackFunction();
}
functionB(functionA);
Here, functionA can be called as Callback Function because it is passed as an argument in functionB for later execution. Generally later execution means functionA will be called after the other codes in functionB.
Now let's use the callback function to solve the issue that we discussed earlier in this article.
function add(a, b, callbackFunction) {
setTimeout(() => {
const sum = a + b;
callbackFunction(sum);
return sum;
}, 2000);
}
function display(value) {
console.log(value);
}
const result = add(10, 5, display);
Output:
15
In this example, display function is a callback function because it is passed as an argument in function add and is executed after the add function completed the addition of two numbers. That is why we get 15 as an output.
Callbacks are used often in JavaScript, and I hope this article helps you understand what they are and how to actually work with them.