JavaScript · Chapter 49 of 55

JavaScript Callbacks

A callback is a function passed as an argument to another function, to be executed later — often after some operation completes. Callbacks are the foundation of asynchronous JavaScript.

While powerful, deeply nested callbacks (sometimes called 'callback hell') can become hard to read, which is why Promises and async/await were introduced as cleaner alternatives.

Synchronous callbacks

`arr.forEach(item => console.log(item))` uses a callback that runs immediately for each element — this is a synchronous use case.

Asynchronous callbacks

`setTimeout(() => console.log('done'), 1000)` uses a callback that runs later, after a delay, demonstrating async behaviour.

Example 1 (javascript)
function processUser(name, callback) {
  let greeting = "Hello " + name;
  callback(greeting);
}
processUser("Tom", msg => console.log(msg));
Output
Hello Tom

The callback function is invoked with the result once processing finishes.

Example 2 (javascript)
setTimeout(() => {
  console.log("Executed after delay");
}, 100);
console.log("Executed first");
Output
Executed first
Executed after delay

setTimeout schedules the callback to run later, so synchronous code runs first.

Key points

  • A callback is a function passed to and invoked by another function.
  • Callbacks enable async operations like timers and network requests.
  • Deeply nested callbacks create hard-to-read 'callback hell'.
  • Promises and async/await were created to improve on callback patterns.
💡 Note: Not all callbacks are asynchronous — array methods like map/forEach use synchronous callbacks.

📝 Quick Quiz

1. What is a callback?

2. What problem can excessive nested callbacks cause?

3. What replaced deeply nested callbacks in modern JS?