Callbacks

Topic 2 of 5 in Asynchronous code5 min readBeginnerFree course

Overview

Some work takes time: waiting for a timer, a click or a network response. Instead of stopping everything, JavaScript lets you hand over a callback — a function to run once the work is done.

JavaScript
setTimeout(() => {
  console.log('One second later');
}, 1000);

console.log('This runs first');

Think of ordering food at a counter and being given a buzzer. You don’t stand at the counter staring at the kitchen; you go and sit down, and the buzzer calls you back when the food is ready. The callback is your buzzer.

setTimeout(cb, 1000) registers the callback and returns at once at 0 ms; console.log(‘This runs first’) runs straight after; the callback runs about a second later. The browser waits while your other code keeps running.

Synchronous and asynchronous callbacks

Not every callback is about waiting. Array methods take callbacks too, though they run straight away:

JavaScript
const prices = [4, 8, 15];
const withTax = prices.map((p) => p * 1.2); // map calls the callback 3 times, right now
console.log(withTax); // already done
Synchronous callbacks Asynchronous callbacks
Run before the function returns Run later, after your current code has finished
map, filter, forEach, sort setTimeout, addEventListener, older file and network APIs

The difference matters for ordering. Code after an asynchronous call doesn’t wait for its callback.

Callbacks you already know

JavaScript
button.addEventListener('click', () => {
  console.log('Clicked!'); // runs every time the button is clicked
});

setInterval(() => {
  console.log('tick');     // runs every second
}, 1000);

A classic mistake: using the result too early

JavaScript
let data;
setTimeout(() => {
  data = 'loaded';
}, 1000);

console.log(data); // undefined — the callback hasn't run yet!

The value only exists inside the callback (or after it runs). Any code that needs it must go in the callback, or be called from it:

JavaScript
setTimeout(() => {
  const data = 'loaded';
  show(data); // ✓ use it here
}, 1000);

Passing data to a callback

The function that calls your callback decides what arguments it gets. addEventListener passes an event object; map passes the item, index and array. When you write your own function that takes a callback, you decide:

JavaScript
function loadUser(id, callback) {
  setTimeout(() => {
    const user = { id, name: 'Asha' }; // pretend this came from a server
    callback(user);
  }, 500);
}

loadUser(7, (user) => {
  console.log(user.name); // 'Asha'
});

Error-first callbacks

Older APIs — especially in Node.js — use a convention for reporting failure: the callback’s first argument is an error (or null if all went well), and the result comes second:

JavaScript
fs.readFile('notes.txt', 'utf8', (error, text) => {
  if (error) {
    console.error('Could not read file', error);
    return;
  }
  console.log(text);
});

Every caller has to remember to check error. If they forget, failures go unnoticed — one of the reasons promises were invented.

Callback hell

When each step depends on the one before, callbacks nest deeper and deeper:

JavaScript
loadUser(id, (user) => {
  loadCourses(user, (courses) => {
    loadProgress(courses, (progress) => {
      render(progress);
    });
  });
});

Add error handling at every level, and the code drifts further right — a shape nicknamed the “pyramid of doom”. It’s hard to read, hard to change, and easy to get wrong:

  • errors must be handled separately at every step;
  • running steps in parallel and waiting for all of them needs manual counting;
  • a buggy library might call your callback twice — or never.

There’s a better way. The next topic shows how promises flatten this into a readable chain:

loadUser(id).then(loadCourses).then(loadProgress).then(render).catch(showError);

Callbacks are still everywhere — event listeners and array methods are callbacks, and that’s perfectly fine. It’s sequences of asynchronous steps where promises and async/await shine.

Exercise

Delayed greeting

Write greetLater(name, ms, done) that waits ms milliseconds, then calls done with the text Hello, <name>!. Call it so the greeting is logged after 1 second.

JavaScript
function greetLater(name, ms, done) {
  // your code here
}

Summary

  • A callback is a function you pass to another function to call later.
  • Synchronous callbacks (like map) run straight away; asynchronous ones (like setTimeout) run later.
  • setTimeout runs its callback after a delay without blocking other code.
  • Async callbacks often follow the error-first style: (error, result) => { … }.
  • Deeply nested callbacks are hard to read — promises fix that.