Callbacks & Higher-Order Functions — JavaScript interview guide
Callbacks & Higher-Order Functions
A callback is a function passed into another function to be called later. Functions that take or return functions are higher-order functions.
See it run
Press Play, or step with Next. Watch the highlighted line, the Call Stack and memory change together.
A callback is a function you hand over to be called later
1function fetchData(callback) {2setTimeout(() => {3callback("data loaded");4}, 1000);5}6▶fetchData((msg) => {8console.log(msg);9});10console.log("waiting...");
| fetchData | ƒ fetchData() |
| callback | ƒ (msg) => … |
empty
Waits until the Call Stack is empty. Microtasks always go first.
empty
empty
nothing printed yet
What happens:We pass an arrow function INTO fetchData. Inside, it is just a parameter called callback. fetchData is a higher-order function.
Tip: click the box and use ← → keys to step, space to play.
Explained simply
Callbacks
map, filter, addEventListener and setTimeout all take callbacks. Async callbacks run later, through the event loop.
Callback hell and inversion of control
Nesting many async callbacks makes code hard to read and handle errors in. You also hand control to another function and trust it to call you once, with the right data.
Promises and async/await solve both problems.
// callback → promise ("promisify")
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
await wait(500);Remember this
- Functions are first-class values in JS.
- Error-first callbacks: (err, data) => {} in Node.js.
- Promisify old callback APIs.
Interview questions
What is callback hell and how do you fix it?
Deeply nested async callbacks. Fix with named functions, promises with chaining, or async/await.
Practice
- Write promisify(fn) for an error-first callback function.
Keep learning
More in Async JavaScript