Skip to content

Callback

In one line

A callback is a function passed into another function as an argument, to be called later when something happens.

In simple words

A callback is a function you hand to another function and say "call this when you are done." The receiving function calls your callback at the right moment — after a computation finishes, after data loads, or when an event occurs.

Callbacks are everywhere in JavaScript because the language is event-driven and asynchronous. For example, addEventListener('click', callback) calls callback every time the user clicks. setTimeout(callback, 1000) calls callback after one second.

When callbacks themselves trigger more callbacks, you can end up with deeply nested code known as "callback hell." Promises and async/await were introduced to make asynchronous code easier to read and write, but callbacks remain a fundamental pattern.

Example

javascript
function greet(name, callback) {
  const message = "Hello, " + name;
  callback(message);
}

greet("Ada", (msg) => {
  console.log(msg); // "Hello, Ada"
});

greet takes a callback as its second argument and calls it with the generated message.

Common confusions

  • Confused with: promise

    The difference: A callback is a function passed to be called later; a promise is an object representing a future value. Promises are composable and avoid callback hell, while callbacks are simpler but harder to chain.

Related terms

Related Resources

Related Lessons

Learn the fundamentals

Deepen your understanding with structured lessons on this topic.

View lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary