Skip to content
BENIBIX Learn

Callback Function

Development🧭 Programming ParadigmsAsynchronous Code

Also known as Callback, Callbacks

A function you give to other code. That code runs it later.

Think of it like

Think of it like leaving your phone number at a shop. They call you when your order is in.

Example

Emma gives setTimeout a callback and a wait of 2 seconds. Then her function runs and shows a message.

Why it matters

Callbacks are used for clicks, timers and file reads. List tools like map take one too.

Definition

A callback is a function you hand to other code, so that code can run it later. You often pass one to a timer, a click handler or a download. When the time comes, the other code calls your function back. Callbacks were the first way to write async code in JavaScript. Many callbacks inside callbacks get hard to read, which is why promises came along.

Example code

javascript
setTimeout(() => console.log("Done!"), 2000);
The arrow function is the callback. It runs after 2 seconds.

Common mistake

Nesting callbacks five deep, each waiting on the last. Use promises or async/await to flatten them.

Key takeaways

  1. 1
    Hand it over. Other code holds it.
  2. 2
    Run later. When the moment comes.
  3. 3
    Nesting hurts. Deep stacks get messy.

Compare