All tutorials
Advanced

Callback Functions

A function passed into another function to be called later.

1. Explanation

JavaScript treats functions as values, so you can pass them as arguments. The receiving function calls back into them when ready. Callbacks are how setTimeout, array methods (map/filter), and old-style async APIs work. Deeply nested callbacks lead to 'callback hell' — solved by Promises and async/await.

2. Example

Try it yourself
Console
Click Run to see output.

3. Expected output

output
Hi Aman
Welcome back!
After 1 sec

4. Common mistakes

  • Calling the callback instead of passing it: setTimeout(fn(), 1000) runs fn immediately
  • Forgetting that callbacks may run asynchronously
  • Nesting callbacks 5 levels deep — refactor to Promises

5. Practice questions

  1. Write forEachItem(arr, cb) that calls cb on each element
  2. Use setTimeout to log numbers 1..3 one second apart
  3. Build a simple event-emitter with on(event, cb)
→ Try more practice problems