What is a Callback in JavaScript?
- A callback function is a function that is passed as an argument to another function and is executed later by that function.
Example:
function addition(a,b,callback)
{
console.log(a+b);
callback(a,b);
}
function multiply(x,y)
{
console.log(x*y);
}
addition(10,20,multiply)
Output:
30
200
How it works?
addition(10, 20, multiply)
↓
a = 10
b = 20
callback = multiply
↓
console.log(a + b)
↓
30
↓
callback(a, b)
↓
multiply(10, 20)
↓
200
Here:
addition() → Main function
↓
receives multiply()
↓
callback = multiply
↓
addition() performs addition
↓
callback(a,b)
↓
multiply(a,b) executes
Why do we need callbacks?
- To execute another function when needed.
- To decide what happens after a task finishes.
- To handle asynchronous operations.
Without callback
Suppose you want to use the same two numbers 10 and 20 for different operations.
function calculate(a, b) {
console.log(a + b);
}
calculate(10, 20);
Here, it only perform addition.
If later you want subtraction, you would need another function:
function calculateSub(a, b) {
console.log(a - b);
}
calculateSub(10, 20);
And for multiplication, another one:
function calculateMul(a, b) {
console.log(a * b);
}
calculateMul(10, 20);
So we have three different functions.
With Callback
Instead, we can create one common calculate() function and tell it which operation to perform.
function calculate(a, b, operation) {
console.log(operation(a, b));
}
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
function multiply(a, b) {
return a * b;
}
calculate(10, 20, add);
calculate(10, 20, subtract);
calculate(10, 20, multiply);
Output:
30
-10
200
calculate()
/ | \
add subtract multiply
↓ ↓ ↓
10+20 10-20 10*20
↓ ↓ ↓
30 -10 200
Callback with Asynchronous Operations:
A callback is often used with asynchronous operations because we don't know exactly when the operation will finish.
Example:
console.log("Start");
setTimeout(function() {
console.log("Task completed");
}, 2000);
console.log("End");
Output:
Start
End
Task Completed
Start
↓
setTimeout() starts
↓
JavaScript doesn't wait
↓
End
↓
2 seconds completed
↓
Callback executes
↓
Task completed
What is Callback Chaining?
Callback chaining means passing one callback to another function, and that function then uses another callback to call the next function.
Example:
function add(a, b, callback) {
console.log(a + b);
callback(a, b, multiplication);
}
function sub(x, y, multi) {
console.log(x - y);
multi(x, y);
}
function multiplication(a, b) {
console.log(a * b);
}
add(50, 2, sub);
Output:
52
48
100
add(50, 2, sub)
↓
add()
↓
50 + 2 = 52
↓
callback = sub
↓
sub(50, 2, multiplication)
↓
50 - 2 = 48
↓
multi = multiplication
↓
multiplication(50, 2)
↓
50 × 2 = 100
Top comments (0)