Chapter XVI · Asynchronous JavaScript

Callbacks

A callback function is passed as an argument to an asynchronous operation, to be executed once the operation finishes.

01 How It Works

Think of giving your phone number to a store clerk so they can call you when your item arrives.

The callback reference is stored by the runtime and pushed into a task queue when the async operation completes.

example.js
function fetchData(callback) {
  setTimeout(() => {
    callback("Data loaded");
  }, 1000);
}
fetchData(msg => console.log(msg));
  1. 1. Pass callback function into async function call.

  2. 2. Async API executes operation in background.

  3. 3. Callback is invoked when data or timer is ready.

02 Practical Example

Here is how you might see this concept applied in real-world code:

practical.js
setTimeout(function() {
  console.log("Callback executed after timer");
}, 500);

Key Takeaway

Callbacks form the foundational pattern for handling asynchronous events in JavaScript.

Related Concepts