JavaScript lesson · 19 min

JavaScript Callback Functions

Pass a function into another function so code can decide what to do later.

Code runs locally in your browser

What you will practice

  • Understand functions as values.
  • Pass a callback into another function.
  • Use callbacks with array methods.

What this means

A callback is a function you give to another function. The receiving function calls it at the right time.

JavaScript treats functions as values. You can store them in variables, pass them as arguments, and return them from other functions.

Many array methods use callbacks. `map`, `filter`, `find`, and `reduce` all ask you to provide a function that describes what should happen to each item.

If this is your first time seeing this

A callback is a function passed into another function.

Callbacks let you describe what should happen without doing that work immediately.

Mini glossary

Callback
A function given to another function to call later or for each item.
Function value
A function treated like data that can be passed around.
Higher-order function
A function that receives or returns another function.

Example from everyday life

A callback is like leaving instructions with a delivery desk: when the package arrives, send me a text. You do not do the future work now; you give instructions for what should happen later.

How it works step by step

  1. The code defines `formatTool`, a function that formats one tool name.
  2. `showTools` accepts a list and a callback named `formatter`.
  3. Inside `showTools`, `map` calls the formatter for each item.
  4. The same `showTools` function could use a different formatter later.

Where you will use this

  • A button click handler is a callback that runs when the user clicks.
  • Array methods use callbacks to transform or filter data.
  • A timer uses a callback to run code after a delay.

Before you run the code

Callbacks are one of the core ideas in JavaScript. They can feel strange because you are passing behavior, not just data.

When reading a callback, ask: who receives this function, and when will they call it?

Common beginner mistakes

  • Calling the callback too early instead of passing the function itself.
  • Forgetting what arguments the receiving function will pass to the callback.
  • Writing callback chains that are hard to read.

Run in browser

Try the example

Console output
Run the code to see console output here.
Exercise checks0 of 2 checks passed.
WaitingPasses a formatter callback
WaitingKeeps original data intact

Code runs locally in a temporary browser worker with a timeout. It is not sent to Lumio analytics or executed on the server.

Try changing this next

  • Change `formatTool` to return lowercase names.
  • Pass an inline arrow function into `showTools`.
  • Add another tool to the list.