JavaScript Callbacks
A callback is a function passed to another function so it can be run later, often after an asynchronous task finishes.
What is a callback?
In JavaScript, functions are values, which means you can pass one function as an argument to another. A function passed in this way is called a callback, because the receiving function will call it back at the right moment. Callbacks are the foundation of asynchronous programming: they let you say what should happen once a slow task, such as reading a file or fetching data, has completed.
A simple synchronous callback
<!DOCTYPE html>
<html>
<body>
<h2>A Simple Callback</h2>
<script>
function processUser(name, callback) {
const greeting = "Hello, " + name;
callback(greeting);
}
processUser("Ada", function (message) {
console.log(message); // "Hello, Ada"
});
</script>
</body>
</html>Why callbacks matter for async code
Some operations do not finish instantly. Timers, network requests, and file access all take time, and JavaScript does not pause and wait for them. Instead you hand it a callback that runs once the operation is done, allowing the rest of your program to keep going in the meantime.
An asynchronous callback with setTimeout
<!DOCTYPE html>
<html>
<body>
<h2>Asynchronous Callback</h2>
<script>
console.log("Start");
setTimeout(function () {
console.log("This runs later");
}, 1000);
console.log("End");
// Output order:
// Start
// End
// This runs later
</script>
</body>
</html>Callback hell
When one asynchronous step depends on the result of another, callbacks start to nest inside callbacks. A few levels deep this becomes hard to read and maintain, a problem widely known as callback hell or the pyramid of doom. This is the main reason Promises and async/await were introduced.
Nested callbacks become hard to follow
<!DOCTYPE html>
<html>
<body>
<h2>Callback Hell</h2>
<script>
getUser(1, function (user) {
getOrders(user, function (orders) {
getDetails(orders[0], function (details) {
console.log(details);
// logic keeps drifting further right
});
});
});
</script>
</body>
</html>- Callbacks are just functions passed as arguments to be called later.
- They let asynchronous tasks report back when they finish.
- Deeply nested callbacks are hard to read and reason about.
- Promises and async/await were created to solve these problems.