Skip to main content
FREE Mock interview & resume review with Sumit. Free right now, no payment needed.Book a slot

Callbacks & Higher-Order Functions — JavaScript interview guide

7 / 23Async JavaScriptMedium priorityEasy 20 min

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

Execution phaseStep 1/9
script.js
1function fetchData(callback) {
2 setTimeout(() => {
3 callback("data loaded");
4 }, 1000);
5}
6
▶fetchData((msg) => {
8 console.log(msg);
9});
10console.log("waiting...");
Call Stack
last in, first out
Global
fetchData(cb)running
Memory / Scope
Global
fetchDataƒ fetchData()
fetchData()
callbackƒ (msg) => …
Web APIs (browser)
runs outside JS

empty

Event Loop

Waits until the Call Stack is empty. Microtasks always go first.

Microtask Queue
promises · high priority

empty

Callback Queue
setTimeout, events

empty

Console

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

  1. Write promisify(fn) for an error-first callback function.

Keep learning