JS Callbacks
A callback is a function passed to another function as an argument, to be called back later. It's the original async pattern in JavaScript and still used everywhere — map, event listeners, timers.
The basic shape
JS
function greet(name, cb) {
cb(`Hello, ${name}!`);
}
greet("Ada", (msg) => console.log(msg)); // "Hello, Ada!"
Synchronous callbacks
Array methods take callbacks but run them right away:
JS
[1, 2, 3].map(n => n * 2); // [2, 4, 6] [1, 2, 3].filter(n => n > 1); // [2, 3] [1, 2, 3].reduce((sum, n) => sum + n); // 6
Asynchronous callbacks
The traditional pattern: "do something slow, call back when done."
JS
setTimeout(() => console.log("later"), 1000);
button.addEventListener("click", e => console.log("clicked"));
// Node-style error-first
fs.readFile("a.txt", (err, data) => {
if (err) return console.error(err);
console.log(data.toString());
});
Callback hell — and why Promises exist
JS
// 😱 deeply nested error handling
loadUser(id, (err, user) => {
if (err) return done(err);
loadOrders(user.id, (err, orders) => {
if (err) return done(err);
loadShipping(orders, (err, shipping) => {
if (err) return done(err);
done(null, { user, orders, shipping });
});
});
});
// 😌 same thing with async/await
const user = await loadUser(id);
const orders = await loadOrders(user.id);
const shipping = await loadShipping(orders);
Tip: Use callbacks for synchronous helpers (map/filter/sort) and DOM events. Use Promises and
async/await for anything network or file-related — modern APIs already return them.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Callbacks!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Double every number with a callback.
const doubled = nums.
(n => n * 2);
Three letters — transforms each item.
Discussion
Loading…