← JavaScript

Functions

What is a callback and what is it for?

Show answer — try answering out loud first

A callback is a function that is passed as an argument to another function so that it can run it later. It's widely used in asynchronous operations and in array methods like map or filter.

In JavaScript, functions are values: you can store them in variables and pass them as arguments. When you pass a function to another function so it "calls it back" at some point, that passed function is a callback.

They are used in two major contexts:

  • Synchronous: methods like map, filter, and forEach take a callback that runs for each element.
  • Asynchronous: operations like setTimeout or server requests take a callback that runs when the task finishes.
// Synchronous callback: runs for each element
const numeros = [1, 2, 3];
numeros.forEach(function (n) {
  console.log(n * 2); // 2, 4, 6
});

// Passing a defined function as a callback
function saludar(nombre) {
  console.log("Hola " + nombre);
}
function procesar(nombre, callback) {
  callback(nombre); // here it "calls back"
}
procesar("Mike", saludar); // "Hola Mike"

// Asynchronous callback
setTimeout(function () {
  console.log("Esto se ejecuta después");
}, 1000);
  • Calling the callback instead of passing it: writing procesar(saludar()) instead of procesar(saludar). With parentheses you run it immediately and pass its result; without parentheses you pass the function itself.
  • Callback hell: nesting many asynchronous callbacks creates hard-to-read code. That's what promises and async/await exist for.

"A callback is a function I pass to another function as an argument so it runs it when needed. I use them all the time with array methods like map or filter, where the callback runs for each element, and also in asynchronous code like setTimeout. An important detail is passing the function without parentheses, because with parentheses I run it instead of passing it."

Quick challenge

Write a function repetir(n, callback) that calls the callback n times, passing it the current repetition number (starting at 1).

See answer
function repetir(n, callback) {
  for (let i = 1; i <= n; i++) {
    callback(i);
  }
}
repetir(3, (i) => console.log("Repetición " + i));
// Repetición 1
// Repetición 2
// Repetición 3