βοΈJavaScript: Async & Advanced
Asynchrony is the other half of the JS interview. If you can explain the event loop, promises, and async/await clearly β with the microtask/macrotask ordering β you're ahead of most candidates.
4.1The Event Loop, Call Stack & Queues
JavaScript is single-threaded: one call stack, one thing at a time. Yet it handles timers, network, and events without blocking. How?
The moving parts:
- Call stack β where function frames run (LIFO).
- Web APIs β the browser (not JS) handles
setTimeout,fetch, DOM events, off-thread. - Callback / Task queue (macrotasks) β completed
setTimeout, events, I/O callbacks wait here. - Microtask queue β resolved Promise
.then/catch/finally,queueMicrotask,awaitcontinuations. Higher priority. - Event loop β when the stack is empty, it drains all microtasks, then takes one macrotask, then drains microtasks again, and so on.
console.log("1");
setTimeout(() => console.log("2"), 0); // macrotask
Promise.resolve().then(() => console.log("3")); // microtask
console.log("4");
// Output: 1, 4, 3, 2
Synchronous code runs first (1, 4). Then the loop empties all microtasks (3) before any macrotask (2) β even with setTimeout(β¦, 0). This ordering question is extremely common.
Key insight: microtasks always run before the next macrotask. A flood of promise callbacks can starve setTimeout/rendering.
4.2Callbacks & Callback Hell
A callback is a function passed to be invoked later. Before promises, async flow nested callbacks:
getUser(id, (user) => {
getOrders(user, (orders) => {
getDetails(orders[0], (details) => { /* pyramid of doom */ });
});
});
Problems: deep nesting ("callback hell"), scattered error handling (each callback checks its own error), and inversion of control (you trust a library to call your callback correctly, once). Promises fix all three.
4.3Promises
A Promise is an object representing the eventual result of an async operation. It has three states: pending β fulfilled (resolved with a value) or rejected (with a reason). Once settled, it never changes.
const p = new Promise((resolve, reject) => {
setTimeout(() => resolve("done"), 100);
});
p.then(v => console.log(v)) // "done"
.catch(err => console.error(err)) // handles any rejection in the chain
.finally(() => console.log("cleanup"));
- Chaining: each
.thenreturns a new promise, flattening nesting into a readable pipeline. Returning a value passes it on; returning a promise waits for it. - Error propagation: one
.catchat the end handles rejections from anywhere earlier in the chain. - A
.thenalways runs as a microtask, even if the promise is already resolved.
4.4Promise Combinators
Promise.all([a, b, c]) // waits for ALL; rejects fast if ANY rejects
Promise.allSettled([a, b, c]) // waits for all; never rejects β array of {status, value/reason}
Promise.race([a, b]) // settles as soon as the FIRST settles (fulfill or reject)
Promise.any([a, b]) // first FULFILLED; rejects only if all reject (AggregateError)
allβ parallel requests where you need every result (fails fast).allSettledβ parallel where you want every outcome regardless of failures (dashboards).raceβ timeouts (race([fetch(), timeout()])).anyβ first success wins (fastest mirror).
Running independent requests in parallel with Promise.all instead of sequential awaits is a classic perf fix.
4.5async / await
Syntactic sugar over promises that lets you write async code that reads synchronously.
async function loadDashboard(id) {
try {
// parallel β start both, then await
const [user, orders] = await Promise.all([getUser(id), getOrders(id)]);
return { user, orders };
} catch (err) {
console.error("failed", err);
throw err;
}
}
- An
asyncfunction always returns a promise.return xresolves it withx;throwrejects it. awaitpauses the function until the promise settles, unwrapping the value β but the thread is not blocked; the event loop keeps running other code.- Use
try/catchfor errors (vs.catch). - Pitfall: sequential
awaits that don't depend on each other run slower than needed β parallelize withPromise.all. awaitin a loop is sequential; usePromise.all(items.map(async β¦))for concurrency.
4.6setTimeout, setInterval & the "0ms" Myth
setTimeout(fn, 0)doesn't run immediately β it queues a macrotask that runs after the current stack clears and all microtasks drain. The delay is a minimum, not a guarantee.setIntervalcan drift and stack up if the callback is slow; a recursivesetTimeoutis often safer.requestAnimationFrameruns before the next repaint (~60fps) β use it for animations, notsetTimeout.
4.7Debounce & Throttle
Two closure-based techniques to rate-limit expensive handlers (scroll, resize, keypress, search).
- Debounce β wait until activity stops for N ms, then fire once. (Search-as-you-type: fire after the user pauses.)
- Throttle β fire at most once every N ms during continuous activity. (Scroll/resize handlers.)
function debounce(fn, delay) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
}
function throttle(fn, limit) {
let waiting = false;
return (...args) => {
if (waiting) return;
fn(...args);
waiting = true;
setTimeout(() => (waiting = false), limit);
};
}
Both are quintessential closure use-cases β the timer/waiting state is private and persists across calls.
4.8Event Propagation & Delegation
A DOM event travels in phases: capturing (window β target) then bubbling (target β window). Most handlers listen on the bubbling phase.
event.stopPropagation()halts travel;event.preventDefault()cancels the default action (form submit, link nav) but still bubbles.- Event delegation: attach one listener to a common ancestor and read
event.targetinstead of binding a listener per child. Efficient for large/dynamic lists.
list.addEventListener("click", (e) => {
const item = e.target.closest("li");
if (item) handle(item.dataset.id);
});
4.9Currying, Partial Application & Composition
- Currying β transform
f(a, b, c)intof(a)(b)(c); each call takes one arg and returns a function until all are supplied. - Partial application β pre-fill some arguments now, the rest later (
fn.bind(null, a)). - Composition β combine small functions:
compose(f, g)(x) = f(g(x)).
const add = a => b => a + b; // curried
const add5 = add(5);
add5(3); // 8
Useful for building configurable, reusable functions and is the backbone of functional-programming utilities.
4.10Memoization
Caching a function's result by its arguments so repeated calls are instant β a closure holding a cache:
function memoize(fn) {
const cache = new Map();
return (arg) => {
if (cache.has(arg)) return cache.get(arg);
const result = fn(arg);
cache.set(arg, result);
return result;
};
}
Same idea powers React.memo, useMemo, and reselect selectors. Trade memory for speed; watch cache growth.
4.11ES Modules
export const x = 1; // named export
export default function App(){} // default export
import App, { x } from "./file"; // import default + named
- ESM (
import/export) is static β the dependency graph is known at build time, enabling tree-shaking (dead-code elimination) and bundler optimization. - CommonJS (
require/module.exports) is dynamic and runtime-evaluated (Node's legacy system). - Modules have their own scope (no global leakage) and run in strict mode; imports are live read-only bindings, not copies.
4.12Generators & Iterators (brief)
A generator (function*) can pause with yield and resume, producing values lazily:
function* ids() { let i = 1; while (true) yield i++; }
const gen = ids();
gen.next().value; // 1
gen.next().value; // 2
Any object with a Symbol.iterator is iterable (works with forβ¦of, spread). Generators power lazy sequences and underpinned libraries like redux-saga.
4.13Error Handling
try {
risky();
} catch (err) {
if (err instanceof TypeError) { /* specific */ }
report(err);
} finally {
cleanup(); // always runs
}
- Synchronous errors β
try/catch. Promise rejections β.catchortry/catcharoundawait. - Throw
Errorobjects (they carry a stack), not strings. - Unhandled promise rejections should be caught globally (
window.onunhandledrejection) in production. - Fail loudly in dev, degrade gracefully in prod (fallback UI, retries).
π§ Quiz: JavaScript: Async & Advanced
17 questions1What does this print? console.log(1); setTimeout(() => console.log(2), 0); Promise.resolve().then(() => console.log(3)); console.log(4);
2Which Promise combinator rejects as soon as ANY input rejects?
3An async function always returns:
4You have two independent async calls. The fastest correct approach is:
5Debounce vs throttle: to fire a search only after the user STOPS typing for 300ms, you use:
6Event delegation means:
7Which browser phase enables event delegation to work?
8How does JavaScript's garbage collector decide what to free?
9What does a generator function (function*) let you do?
10An object is 'iterable' (usable in for...of) when it:
11What does currying transform a function into?
12A key difference between WeakMap and Map is that WeakMap:
13Debounce and throttle differ in that:
14Why isn't spread ({ ...obj }) a deep copy?
15Which is a common JavaScript memory-leak cause?
16When should you reach for a Web Worker?
17In the event loop, which drains completely before the next macrotask runs?