JavaScript Callbacks
"I will call back later!"
A callback is a function passed as an argument to another function.
The receiving function decides when to use (call) the callback.
A callback can be called immediately, later, once, or many times.
By themselves, callbacks are neither synchronous nor asynchronous.
They are simply a way to let one function execute another function.
Why Use Callbacks?
Callbacks make functions more flexible.
Instead of hardcoding what should happen next, a function can let the caller decide by supplying a callback.
Example
Pass a function as an argument:
// A Greet Function
function greet(name, callback) {
callback("Hello " + name);
}
// A Display Function
function display(message) {
document.getElementById("demo").innerHTML = message;
}
// Call greet() with a callback function (display)
greet("John", display);
Try it Yourself »
The display function is the callback.
The greet() function decides when to call it.
Synchronous Callbacks
Most callbacks execute immediately.
These are called synchronous callbacks because they run before the current function returns.
Example
// Calculate Function
function calculate(x, y, operation) {
return operation(x, y);
}
// Add Function
function add(a, b) {
return a + b;
}
// Call calculate() with add as callback
let result = calculate(5, 3, add);
Try it Yourself »
Note
The callback runs immediately while calculate() is executing.
No asynchronous behavior is involved.
Built-in Synchronous Callbacks
Many JavaScript methods use synchronous callbacks.
| Method | Callback Called | Asynchronous? |
|---|---|---|
forEach() |
Once for each element | No |
map() |
Once for each element | No |
filter() |
Once for each element | No |
reduce() |
For each element | No |
sort() |
To compare values | No |
Timing Problems
You cannot see a result before it is computed.
Example
let result;
setTimeout(function() {
result = 5;
}, 1000);
// What is result here?
Try it Yourself »
The result is undefined because the async code has not finished yet.
The Callback Idea
The solution to the problem above, is to give JavaScript a callback function to call after the result is ready.
A callback is a function passed as an argument to another function.
This technique allows a function to call another function.
Example
function done(value) {
myDisplayer(value);
}
setTimeout(function() {
done(5);
}, 1000);
// What is result here?
Try it Yourself »
The value is used inside the callback.
This works because the callback runs later.
Asynchronous Callbacks
Callbacks are also commonly used with asynchronous APIs.
In these cases, the callback runs after the asynchronous operation has completed.
The callback is not what makes the operation asynchronous.
The asynchronous API decides when to call the callback.
Example
// Set a Timeout
setTimeout(function () {myDisplayer("Finished!")}, 3000);
Try it Yourself »
In the example above:
myDisplayer is a callback function passed as an argument to setTimeout().
3000 is the number of milliseconds before myDisplayer will be called.
The browser waits three seconds before calling the callback.
The delay is created by setTimeout(), not by the callback itself.
Note
When you pass a function as an argument, remember not to use parenthesis.
Right: setTimeout(myFunction, 3000)
Wrong: setTimeout(myFunction(), 3000)
Event Handling
Callbacks are often used in JavaScript, especially in event handling:
User interactions, such as button clicks or key presses, can be handled by providing a callback function to an event listener.
Example
document.getElementById("myButton").addEventListener("click", displayDate);
Try it Yourself »
In the example above, displayDate is a callback function passed
as an argument to the addEventListener() method.
displayDate will be called when a user clicks the button with id="myButton".
Sequence Control
Sometimes you would like to have better control over when to execute a function.
Suppose you want to do a calculation, and then display the result.
You could first call the calculator function myCalculator,
and then call the display function myDisplayer:
Example
// Funtion to display something
function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}
// Function to calculate a sum
function myCalculator(num1, num2) {
let sum = num1 + num2;
return sum;
}
// Call the calculator
let result = myCalculator(5, 5);
// Call the displayer
myDisplayer(result);
Or, you could call the calculator function myCalculator,
and let the calculator function call the display function myDisplayer:
Example
// Funtion to display something
function myDisplayer(some) {
document.getElementById("demo").innerHTML
= some;
}
// Function to calculate a sum
function myCalculator(num1, num2) {
let sum = num1 + num2;
myDisplayer(sum);
}
// Call the calculator
myCalculator(5, 5);
The problem with the first example above, is that you have to call two functions to display the result.
The problem with the second example, is that you cannot prevent the calculator function from displaying the result.
Now it is time to bring in a callback.
Using a callback, you could call the calculator function (myCalculator)
with a callback (myCallback), and let the calculator function run the callback after the calculation is finished:
Example (Callbacks)
function myDisplayer(some) {
document.getElementById("demo").innerHTML
= some;
}
function myCalculator(num1, num2, myCallback) {
let sum = num1 + num2;
myCallback(sum);
}
myCalculator(5, 5, myDisplayer);
Try it Yourself »
In the example above, myDisplayer is used as a callback function.
It is passed to myCalculator() as an argument.
Callback Chains
Sometimes one callback starts another operation that uses another callback.
This can lead to deeply nested, complex and hard-to-read code.
When callbacks get deep, debugging is difficult. The logic moves from left to right and becomes difficult to follow.
This is often referred to as "callback hell" or the "pyramid of doom".
Example
step1(function(result1) {
step2(result1, function(result2) {
step3(result2, function(result3) {
display(result3);
});
});
});
Note
Promises and async/await were introduced to make asynchronous code easier to read and maintain.
Summary
- A callback is a function passed to another function.
- Callbacks can be synchronous or asynchronous.
- The callback itself does not make code asynchronous.
- Many JavaScript methods use synchronous callbacks.
- Asynchronous APIs often use callbacks to handle results.
- Promises and
async/awaitbuild on the same idea while making asynchronous code easier to write.
Callback is Not Asynchronous
- A callback is just a function.
- It may be called immediately (like map() or sort()).
- It may be called later by an asynchronous API (like setTimeout() or fetch()).
- The API (not the callback) is what introduces the asynchronous behavior.
Callback Alternatives
Asynchronous callback solutions are difficult to write and difficult to debug.
Because of this, modern asynchronous JavaScript do not use callbacks.
Modern JavaScript offers superior alternatives for handling asynchronous operations, using Promises and the async/await syntax, which provide a cleaner flow and better error handling.
When to Use a Callback?
Callbacks are still important to understand.
Where callbacks really shine are in asynchronous functions, where one function has to wait for another function (like waiting for a file to load).