Skip to main content

What is a callback function?

A callback function is a function passed as an argument to another function, so it runs later, after some event happens or an operation finishes.

In other words:

"I'm handing you a function, call it when you're ready."


The simplest example

javascript
function sayHello(name) { console.log(`Hello, ${name}!`); } function greet(callback) { console.log('Getting ready to say hello...'); callback('Tim'); } greet(sayHello);

What happens:

  1. sayHello is the callback passed into greet;
  2. greet calls it internally;
  3. The console prints:
javascript
Getting ready to say hello... Hello, Tim!

Callback as an anonymous function

You don't have to pass a named function, you can pass an anonymous one:

javascript
setTimeout(() => { console.log('2 seconds have passed'); }, 2000);

Here:

  • () => console.log(...) is the callback function,
  • It will be called after 2 seconds, not right away.

How this works

  • JavaScript accepts a callback as a value (since functions are "first-class objects");
  • It does not call it right away, but stores it for a later call;
  • When the right moment comes (a timer fires, a request finishes, an event happens), the engine calls that function.

Real-world examples

1. Callback in an event handler

javascript
button.addEventListener('click', () => { console.log('Button clicked!'); });

Here the callback is called by the browser on a click.


2. Callback when loading data

javascript
fetch('/user') .then(response => response.json()) .then(data => console.log(data));

The .then() callbacks are called after the asynchronous request finishes.


3. Callback as a step in an algorithm

javascript
function calculate(a, b, callback) { const result = a + b; callback(result); } calculate(2, 3, (sum) => { console.log('Result:', sum); });

The problem: "Callback Hell"

If there are too many callbacks, the code becomes nested and unreadable:

javascript
getUser(id, user => { getPosts(user, posts => { getComments(posts, comments => { console.log('Done!'); }); }); });

This is called callback hell.


Solving the problem

To avoid "hellish" nesting, we got:

  • Promises:

    javascript
    getUser(id) .then(getPosts) .then(getComments) .then(console.log);
  • async/await:

    javascript
    const user = await getUser(id); const posts = await getPosts(user); const comments = await getComments(posts); console.log('Done!');

A simple analogy

Imagine you're ordering a pizza. You say: "Call me when it's ready."

That "call" is the callback.


SUMMARY

TermDescription
Callback functionA function passed into another function to run later
When it's calledAfter an event, an operation finishes, or a condition is met
Usage examplessetTimeout, addEventListener, fetch().then()
ProblemDeep nesting ("callback hell")
Modern alternativesPromise, async/await

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.