Callback Function in JavaScript: Sync vs Async

Easy100% Free~15 mins#callbacks#higher-order-functions#settimeout#event-loop#async
Interview Answer (30-Second Summary)

A callback function in JavaScript is a function passed as an argument to another function, which calls it back later. Some APIs call it synchronously, like Array.prototype.map, and some asynchronously, like setTimeout or an event listener, so the same pattern can run now or after the current code finishes.

Key Learning Objectives
✓

Define a callback function and recognise one in array methods, timers and event listeners.

✓

Predict whether a callback runs synchronously or asynchronously from the API that receives it.

✓

Trace how an asynchronous callback waits in the task queue until the call stack is empty.

✓

Explain callback hell, error-first callbacks and how Promises replace nested callbacks.

The Interview Problem

In what order are the four lines printed, and which callbacks run synchronously and which asynchronously?

1function fetchUser(id, onDone) {
2 console.log('fetch', id);
3 setTimeout(() => onDone({ id, name: 'Ada' }), 0);
4}
5
6const doubled = [3, 1, 2].map((n) => n * 2);
7console.log(doubled.join(','));
8
9fetchUser(7, (user) => console.log('got', user.name));
10console.log('after fetchUser');
Predict Console Output
Interactive Challenge

Select the option that matches what this code prints to the console:

6,2,4 / fetch 7 / after fetchUser / got Ada

6,2,4 / fetch 7 / got Ada / after fetchUser

fetch 7 / 6,2,4 / after fetchUser / got Ada

6,2,4 / after fetchUser / fetch 7 / got Ada

V8 Engine Execution Trace
Step 1 of 6 (Line 6)

map calls the arrow callback once per element, synchronously, before map returns: 3 -> 6, 1 -> 2, 2 -> 4.

Call Stack (Top = Active)
Global
Array.prototype.map
(n) => n * 2
Lexical Scope / Bindings
doubled:<uninitialized>
Console Stream
> [empty]

Callback Function in JavaScript Explained

What a Callback Is

A callback is a function passed to another function as an argument, so the receiving function can call it later. This works because functions in JavaScript are values: they can be stored in variables, passed around and returned.

  1. Synchronous callbacks: map, filter, forEach, sort and reduce call their callback right away, once per element, and only return when they are done. That is why 6,2,4 is printed first.
  2. Asynchronous callbacks: setTimeout, event listeners and I/O APIs store the callback and return immediately. The callback is queued as a task and the event loop runs it only when the call stack is empty. So fetchUser prints fetch 7 at once, the script prints after fetchUser, and got Ada comes last, even with a 0 ms delay.
  3. Why it matters: code written after an asynchronous call cannot use its result directly. The result only exists inside the callback, which is why chains of dependent steps nest into callback hell, and why Promises and async/await were added to flatten them.
Common Traps & Mistakes

Assuming every callback is asynchronous. Array methods call their callbacks synchronously.

Expecting a 0 ms setTimeout callback to run before the rest of the current script. It always waits for the call stack to empty.

Calling the function instead of passing it: setTimeout(done(), 0) runs done immediately and passes its return value, not the function.

FAANG Follow-Up Probes
Probe #1

How would you rewrite fetchUser to return a Promise, and how would the caller change?

Probe #2

What is inversion of control with callbacks, and how do Promises reduce that risk?

Probe #3

Why can't a try/catch around fetchUser catch an error thrown inside its asynchronous callback?

Callback Function in JavaScript Interview Questions

Key interview inquiries, edge cases, and architectural follow-ups for Callback Functions.

Q1.
What is a callback function in JavaScript?

A callback is a function you pass to another function as an argument so that function can call it later. map, filter, forEach, setTimeout, addEventListener and Node-style APIs all take callbacks.

It depends on the function that receives them. Array methods such as map and forEach call the callback synchronously, before they return. setTimeout, event listeners and I/O APIs call it later, from the task queue, after the current script has finished.

Callback hell is deeply nested callbacks, where each asynchronous step starts inside the previous one's callback, which makes errors and control flow hard to follow. Promises and async/await flatten the same steps into a chain or straight-line code.

A Node.js convention where the callback's first parameter is an error (or null) and the result comes after it: callback(err, data). The caller checks err before using data, because a thrown error inside asynchronous code cannot be caught by the original try/catch.

A higher-order function is the function that takes or returns another function, like map or setTimeout. The callback is the function being passed in. map is the higher-order function; (n) => n * 2 is its callback.

fetchUser schedules its callback with setTimeout, so the callback waits in the task queue. The event loop only runs it once the call stack is empty, which is after the synchronous console.log('after fetchUser') has run, even with a 0 ms delay.

Wrap it in new Promise((resolve, reject) => ...) and call resolve or reject from inside the callback. For Node error-first callbacks, util.promisify does this for you.

More JavaScript interview questions for freshers