Callbacks

A function passed as an argument to another function, to be called later — the pattern behind array methods, events, and async code.

Purpose

A callback is a function passed as an argument to another function, which calls it at some point — immediately, later, zero times, or many times, depending on what the receiving function does.

Example

function processOrder(item, onComplete) {
  console.log(`Processing ${item}...`);
  onComplete(item);
}

processOrder('book', function (item) {
  console.log(`${item} shipped!`);
});

Where this pattern shows up

  • Array methods: array.map(callback), array.filter(callback), and similar — the callback runs once per element.
  • Event handling: element.addEventListener('click', callback) — the callback runs whenever the event fires, possibly many times or never.
  • Asynchronous code: older Node-style APIs and setTimeout call their callback once, later, after some operation finishes — the origin of “callback-based” async code, largely superseded by promises and async/await (covered later in this tier).

Common mistakes

  • Forgetting that a callback passed to addEventListener or setTimeout runs later, not immediately — code written as if the callback’s result is available right after the call is a common source of confusion until asynchronous lessons make the timing explicit.
  • Passing a function call (callback()) instead of a function reference (callback) where a callback is expected — the former runs the function immediately and passes its return value instead of the function itself.

Runtime notes

A coding pattern, not a language feature — behaves identically anywhere JavaScript runs.

Taught in these lessons

Related reference

Updated 2026-09-03