Quick Scoop

A callback function is a function you pass into another function so it can be run later, usually after some work is finished or an event happens. In simple terms, it lets one piece of code “call back” another piece of code at the right time.

How It Works

Think of it like this:

  • You hand a note to a helper function.
  • The helper does its job first.
  • When it’s done, it runs your note — the callback.

This is very common in JavaScript for things like button clicks, timers, and loading data from a server.

Example

javascript

function greet(name, callback) {
  console.log("Hello " + name);
  callback();
}

function sayGoodbye() {
  console.log("Goodbye!");
}

greet("Alice", sayGoodbye);

Here, sayGoodbye is the callback. It gets passed into greet, and greet runs it after saying hello.

Why It’s Useful

  • It helps control when code runs.
  • It supports asynchronous tasks, like waiting for a network request or a timer.
  • It makes code more flexible because the same function can work with different behaviors passed in as callbacks.

Common Places You’ll See It

  • setTimeout()
  • Event listeners like click or submit
  • Array.prototype.map()
  • Promise.then()

TL;DR

A callback function is just a function passed to another function to be executed later.