JavaScript: from closures to the event loop
JavaScript looks forgiving and behaves precisely. Why does 0.1 + 0.2 !== 0.3? Why does a var inside a loop give every callback the same value? Why does a resolved promise run before setTimeout(fn, 0)? Why is [] + {} a string while {} + [] is a number? Every one of those answers comes from three models — the value model, the scope/prototype model, and the event-loop model — and interviews are built almost entirely out of those three.
This guide follows the roadmap.sh/javascript path in one post, with the questions that actually show up in frontend and full-stack interviews interleaved as self-tests. It is theory-first: coercion rules, the prototype chain, microtasks versus macrotasks, and reachability explain why the idioms work, so you can derive the answer instead of memorising it. Code is small and runnable, and each section ends with practice questions.
The execution model
JavaScript is single-threaded, dynamically typed, garbage-collected, and standardized as ECMAScript. “Single-threaded” means one call stack and one thread of execution per agent; concurrency comes from the host (the browser or Node) scheduling callbacks, not from parallel JavaScript.
Engines do not run your source directly. V8 (Chrome, Node) parses it to an AST, compiles it to bytecode, executes that in a register-based interpreter (Ignition), and promotes hot functions to optimized machine code (TurboFan). That three-stage pipeline is why the first run of a function is slower than the millionth, and why JIT deoptimization exists.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=3pt, minimum width=2.1cm, minimum height=0.68cm, font=\small\ttfamily},
a/.style={->, thick}]
\node[b, fill=blue!10] (src) at (0,0) {source .js};
\node[b, fill=orange!16] (ast) at (3.0,0) {AST};
\node[b, fill=yellow!18] (bc) at (6.0,0) {bytecode};
\node[b, fill=green!14] (jit) at (9.0,0) {optimized};
\draw[a] (src) -- node[above, font=\scriptsize] {parse} (ast);
\draw[a] (ast) -- node[above, font=\scriptsize] {compile} (bc);
\draw[a] (bc) -- node[above, font=\scriptsize] {hot} (jit);
\end{tikzpicture}
The stack holds frames (function calls, each with parameters, locals, and a return address) and the heap holds objects. When the stack is empty, the host can hand the engine the next queued callback. That single sentence is the seed of the entire async model later.
ECMAScript defines the language (types, Object, Promise, Array); the host adds APIs that are not part of the language: the browser has document, fetch, setTimeout, and the DOM; Node has fs, process, and setTimeout too. An interviewer asking “is fetch part of JavaScript?” wants that distinction.
ASolution
Yes — one call stack, one thread of JavaScript execution per agent. Asynchrony comes from the host: timers, network I/O, and events are handed off to browser/Node internals, and their callbacks are queued and run on the same single thread when the stack is free. Web Workers are separate agents with their own stacks, communicating by message passing.
fetch part of JavaScript? Is setTimeout?ASolution
No. Both are host APIs. ECMAScript standardizes the language and built-ins like Promise and Array; the browser and Node provide fetch, setTimeout, document, and so on. That is why setTimeout returns different objects in different hosts and why some APIs exist in Node but not the browser.
Values, types, and coercion
There are eight types: seven primitives — undefined, null, boolean, number, bigint, string, symbol — and object. Primitives are immutable and compared by value; objects are mutable collections of properties and compared by reference.
typeof is almost reliable, with two famous exceptions: typeof null === "object" (a bug from 1995 kept for compatibility) and typeof function === "function" (a callable object gets its own tag). Everything else is truthful, including typeof undeclaredVar === "undefined".
typeof 1 // "number"
typeof 1n // "bigint"
typeof "x" // "string"
typeof Symbol() // "symbol"
typeof undefined // "undefined"
typeof null // "object" <- legacy bug
typeof {} // "object"
typeof [] // "object" <- arrays are objects
typeof function(){} // "function"
Numbers are IEEE-754 binary64. One sign bit, 11 exponent bits, 52 fraction bits, so integers are exact only up to \(2^{53}-1\), the safe integer limit. Most decimal fractions are not representable, which is the arithmetic you already know:
\[ \text{value} = (-1)^{s}\times\left(1 + \sum_{i=1}^{52} b_i 2^{-i}\right)\times 2^{\,e-1023} \]
0.1 + 0.2 // 0.30000000000000004
Number.MAX_SAFE_INTEGER // 9007199254740991 (2^53 - 1)
2 ** 53 === 2 ** 53 + 1 // true -- precision lost
Number.isInteger(2.0) // true -- 2.0 has no fractional part
NaN === NaN // false -- NaN is not equal to itself
Object.is(NaN, NaN) // true
Object.is(0, -0) // false
Use Number.EPSILON or Math.abs(a - b) < 1e-9 for float comparison, BigInt (123n) for integers beyond the safe range, and never floats for money.
Truthiness has exactly eight falsy values: false, 0, -0, 0n, "", null, undefined, and NaN. Objects — including [], {}, and new Boolean(false) — are always truthy.
Coercion. == runs the abstract equality algorithm, which coerces with its own rules; === never coerces. The notorious cases follow from ToNumber and ToPrimitive:
null == undefined // true
null == 0 // false
"" == 0 // true ("" -> 0)
"0" == 0 // true
[] == 0 // true ([] -> "" -> 0)
[] == ![] // true (both sides become 0)
[1] == 1 // true
[] + {} // "[object Object]" (both to string)
The warning is simple: use === and Object.is; if you use ==, allow it only for x == null, which matches both null and undefined.
== and ===?ASolution
== performs abstract equality and coerces operands to the same type before comparing ("" == 0 is true). === is strict equality and also compares type, so it returns false for different types. Prefer ===; the only idiomatic == is x == null, which is true for both null and undefined.
typeof null equal to "object"?ASolution
In the original 1995 implementation, objects carried a type tag and null was the null pointer (0x00), which was misread as the object tag. It was never fixed because too much code depends on it. Use value === null to test for null.
NaN, and how do you test for it?ASolution
NaN means “not a number” and results from invalid numeric operations such as Number("abc") or 0 / 0. It is the only value not equal to itself (NaN === NaN is false). Test with Number.isNaN(x) (true only for actual NaN) rather than global isNaN, which coerces its argument and returns true for isNaN("abc").
Variables, hoisting, and scope
Declarations are hoisted before the code runs — the engine scans for var, function declarations, let, const, and class and creates bindings at the top of their scope. What differs is initialization.
varis hoisted and initialized toundefined(function-scoped, redeclarable).letandconstare hoisted but not initialized until their declaration executes — the temporal dead zone (TDZ). Touching them earlier is aReferenceError.functiondeclarations are hoisted together with their body (you can call them above their line).classbehaves likelet: block-scoped, TDZ.
console.log(x) // undefined -- var hoisted + initialized
var x = 1
console.log(y) // ReferenceError: Cannot access 'y' before initialization
let y = 2
greet() // works -- function declaration fully hoisted
function greet() { console.log("hi") }
f() // TypeError -- f is undefined, not the function
var f = function () {}
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=3pt, minimum width=2.3cm, minimum height=0.7cm, font=\small\ttfamily},
a/.style={->, thick}]
\node[b, fill=blue!10] (start) at (0,0) {scope entry};
\node[b, fill=red!12] (tdz) at (3.6,0) {TDZ};
\node[b, fill=green!16] (init) at (7.2,0) {initialized};
\draw[a] (start) -- (tdz);
\draw[a] (tdz) -- node[above, font=\scriptsize] {let/const line} (init);
\node[font=\scriptsize\ttfamily, anchor=north] at (1.8,-0.55) {ReferenceError};
\end{tikzpicture}
Scope is lexical: the global scope, the function scope, and any block scope from { }, if, for, or try. var ignores blocks; let/const respect them. The scope chain is walked outward at lookup time — inner shadows outer, global last.
var a = 1
function outer() {
var b = 2
function inner() {
var c = 3
console.log(a, b, c) // walks global -> outer -> inner
}
inner()
}
outer()
Modules add a fourth scope: every ESM file is its own scope, and top-level declarations do not leak to the global object.
var, let, and const?ASolution
var is function-scoped, hoisted and initialized to undefined, and redeclarable. let and const are block-scoped, hoisted but in a temporal dead zone until their declaration runs, and not redeclarable. const additionally forbids reassignment — but it does not make the value immutable, so a const object can still be mutated.
let hoist?ASolution
Hoisting is the compile-time creation of bindings at the top of a scope. var and function declarations are hoisted and initialized (undefined for var, the function for declarations). let, const, and class are hoisted too but uninitialized, so accessing them before their declaration throws a ReferenceError — that gap is the temporal dead zone.
const object immutable?ASolution
No. const prevents rebinding the name, not mutating the object: const a = []; a.push(1) works. For real immutability use Object.freeze (shallow), or deep-freeze recursively; Object.freeze makes writes silently fail (or throw in strict/ESM code).
Functions and the four rules of this
A function is a first-class object: it has properties, can be passed and returned, and is created with function, an arrow, a method shorthand, or new Function (avoid). Arrow functions differ from function expressions in three ways: no own this (they capture it lexically), no own arguments, and no prototype, so they cannot be constructors.
this is determined at call time by how the function is called — not where it is defined — with one exception: arrows inherit it. There are four binding rules, checked bottom-up from most explicit:
newbinding —new F()creates a fresh object, sets its prototype, bindsthisto it.- Explicit binding —
fn.call(obj),fn.apply(obj, args),fn.bind(obj)setthisyourself. - Implicit binding —
obj.method()setsthis = obj; assigningconst f = obj.methodloses the object and drops to the default. - Default binding — a plain call sets
thistoundefinedin strict mode (which includes classes, modules, and code with"use strict") or the global object (globalThis) in sloppy mode.
const user = {
name: "Ada",
greet() { return this.name },
}
user.greet() // "Ada"
const detached = user.greet
detached() // undefined (this is global/undefined)
user.greet.call({ name: "Bo" }) // "Bo" explicit
const bound = user.greet.bind(user)
bound() // "Ada" bound permanently
function Person(name) { this.name = name } // `new` binding
const p = new Person("Cy") // Person { name: "Cy" }
const arrow = () => this // lexical: whatever `this` was here
call and apply invoke immediately (apply takes an array); bind returns a new function with this (and optionally leading arguments) fixed forever. Arrows cannot be rebound — bind, call, and apply cannot change their this.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=3pt, minimum width=2.5cm, minimum height=0.62cm, font=\small\ttfamily, align=center},
a/.style={->, thick}]
\node[b, fill=green!16] (n) at (0,0) {new};
\node[b, fill=blue!12] (e) at (0,-1.0) {call / apply / bind};
\node[b, fill=orange!16] (i) at (0,-2.0) {obj.method()};
\node[b, fill=red!12] (d) at (0,-3.0) {plain call};
\node[font=\scriptsize, anchor=west, align=left] at (1.9,-3.0) {undefined\\ (strict) / globalThis};
\draw[a] (n) -- (e); \draw[a] (e) -- (i); \draw[a] (i) -- (d);
\end{tikzpicture}
this determined in JavaScript?ASolution
At call time, by the call site, using four rules from most to least explicit: new (fresh object), explicit (call/apply/bind), implicit (obj.method() → obj), and default (plain call → undefined in strict mode, globalThis otherwise). Arrow functions are the exception: they have no own this and capture the enclosing one lexically.
call, apply, and bind?ASolution
call(thisArg, ...args) and apply(thisArg, argsArray) run the function immediately with a chosen this; they differ only in how extra arguments are passed. bind(thisArg, ...args) does not run the function — it returns a new function with this and any leading arguments permanently fixed. Bound functions cannot be re-bound.
const f = obj.method; f() often break?ASolution
The this binding depends on the call site. obj.method() uses implicit binding (this === obj), but extracting the function and calling it plain is a default-bound call, so this is undefined in strict mode. Fix it with obj.method.bind(obj) or by calling through the object.
Closures
A closure is a function together with the lexical environment it was defined in. The function keeps a live reference to the variables of that outer scope, so it can read and write them after the outer function has returned. The outer function’s variables are not copied — they are shared by reference and survive as long as some closure references them.
function makeCounter() {
let count = 0 // captured, not copied
return () => ++count
}
const next = makeCounter()
next() // 1
next() // 2
// `count` is unreachable except through `next`
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=3pt, minimum width=2.3cm, minimum height=0.75cm, font=\small\ttfamily},
a/.style={->, thick}]
\node[b, fill=blue!10] (env) at (0,0) {env \{count: 2\}};
\node[b, fill=orange!16] (fn) at (4.2,0) {next()};
\draw[a] (fn) -- node[above, font=\scriptsize] {captures} (env);
\node[font=\scriptsize, anchor=north] at (2.1,-0.6) {outer scope outlives the outer call};
\end{tikzpicture}
Closures power data privacy (the counter above), partial application, memoization, event handlers, and the module pattern. They are also the source of the classic loop bug:
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i)) // 3, 3, 3
}
// One shared `i`; all callbacks read it after the loop ends at 3.
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i)) // 0, 1, 2
}
// `let` creates a fresh binding per iteration.
The cost: a closure keeps its captured environment alive, so a long-lived closure over a large object is a memory leak waiting to happen. Capture only what you need.
ASolution
A closure is a function bundled with the lexical environment where it was defined, letting it access outer variables after the outer function returns. Practical uses: private state (makeCounter), memoization, partial application via bind, debounce/throttle, and event handlers that remember setup data.
var in a loop produce 3, 3, 3 with setTimeout, but let produces 0, 1, 2?ASolution
var is function-scoped, so all iterations share one i; by the time the timers fire, the loop has finished and i is 3. let is block-scoped and the spec creates a new binding per iteration, so each callback closes over its own i.
ASolution
Yes. A closure keeps its captured variables reachable, so the garbage collector cannot reclaim them while the closure lives. Long-lived closures over large objects, or setInterval callbacks that close over DOM nodes, leak. Capture small values and clear timers/listeners when done.
Prototypes and inheritance
JavaScript does not have classes in the Java sense; class is syntax over prototypal inheritance. Every object has an internal link to another object, its prototype ([[Prototype]], exposed as the non-standard __proto__ getter and the standard Object.getPrototypeOf). A property lookup walks that chain until it finds the key or reaches null. There is no copying: children delegate to the prototype.
const animal = { speak() { return "..." } }
const dog = Object.create(animal) // dog's prototype is animal
dog.speak() // "..." -- found on the prototype
Object.getPrototypeOf(dog) === animal // true
function Dog(name) { this.name = name }
Dog.prototype.speak = function () { return `${this.name} barks` }
new Dog("Rex").speak() // "Rex barks"
Two names are easy to confuse. dog.__proto__ (or [[Prototype]]) is the object it delegates to. Dog.prototype is an ordinary object that new Dog() will become the [[Prototype]] of — it is a property of the constructor, not of instances.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=3pt, minimum width=2.5cm, minimum height=0.7cm, font=\small\ttfamily},
a/.style={->, thick}]
\node[b, fill=orange!16] (o) at (0,0) {rex};
\node[b, fill=blue!12] (p) at (3.6,0) {Dog.prototype};
\node[b, fill=green!14] (op) at (7.4,0) {Object.prototype};
\node[b, fill=black!8] (n) at (10.8,0) {null};
\draw[a] (o) -- node[above, font=\scriptsize] {$\;[[Prototype]]$} (p);
\draw[a] (p) -- (op);
\draw[a] (op) -- (n);
\node[font=\scriptsize, anchor=north] at (5.5,-0.75) {lookup walks left to right};
\end{tikzpicture}
class desugars to exactly this, with extra rules: methods are non-enumerable, the body always runs in strict mode, constructor initializes instances, and extends/super set up the chain. class declarations are not hoisted for use before their line (TDZ).
class Animal {
constructor(name) { this.name = name }
speak() { return `${this.name} makes a sound` }
}
class Dog extends Animal {
speak() { return `${super.speak()} -- specifically, a bark` }
}
new Dog("Rex").speak() // "Rex makes a sound -- specifically, a bark"
instanceof checks the prototype chain. Object.create(null) makes a dictionary with no prototype at all, immune to prototype pollution and useful for hash maps. Prefer Object.hasOwn(obj, key) over obj.hasOwnProperty(key) so a shadowed or absent method cannot break you.
ASolution
It is the linked list of objects an object delegates to. A property lookup checks the object, then its [[Prototype]], then that object’s prototype, and so on until null. It implements inheritance by delegation rather than copying, and instanceof and isPrototypeOf inspect it.
__proto__ and prototype?ASolution
__proto__ (or Object.getPrototypeOf(obj)) is the actual prototype of an object — the object it delegates to. prototype is a property that exists on functions, and it becomes the [[Prototype]] of instances created with new. They are different things; Dog.prototype is not Dog’s prototype.
class relate to prototypes?ASolution
class is syntactic sugar over prototypal inheritance. Methods live on Class.prototype, extends links the two prototypes, and super looks the method up on the parent prototype. Classes add strict mode, non-enumerable methods, and the TDZ, but there is no separate class-based object model underneath.
Objects, arrays, and keyed collections
An object is a mutable set of string-keyed (or symbol-keyed) properties. Object.keys, values, and entries list own enumerable properties; for...in walks enumerable properties including inherited ones, which is why it should be paired with Object.hasOwn. JSON.stringify only serializes own enumerable string keys and drops functions and undefined.
const o = { a: 1, b: 2 }
Object.keys(o) // ["a", "b"]
Object.entries(o) // [["a", 1], ["b", 2]]
for (const k in o) { /* own + inherited */ }
Object.hasOwn(o, "a") // true
JSON.stringify({ a: undefined, b: () => {} }) // "{}"
Map and Set fix the two limits of plain objects: keys of any type (not just strings), and predictable insertion order with a size property.
| Need | Object | Map | Set |
|---|---|---|---|
| Key type | string / symbol | any value | — |
| Ordered iteration | mostly | insertion order | insertion order |
| Size | Object.keys(o).length |
map.size |
set.size |
| Prototype keys | inherited keys exist | none | none |
| Lookup cost | average \(O(1)\) | average \(O(1)\) | average \(O(1)\) |
Common array methods split into mutating (push, pop, shift, unshift, splice, sort, reverse, fill, copyWithin) and non-mutating (slice, concat, map, filter, reduce, flat, flatMap, find, some, every, includes). The classic trap is sort, which mutates and sorts lexicographically by default, so [10, 9, 1].sort() is [1, 10, 9] — pass a comparator: sort((a, b) => a - b). Array.prototype.sort is also not guaranteed stable for primitives in older engines, though ES2019 requires stability.
[1, 2, 3].reduce((acc, n) => acc + n, 0) // 6
[1, [2, [3]]].flat(Infinity) // [1, 2, 3]
[1, 2, 3].at(-1) // 3
[3, 1, 2].sort() // [1, 2, 3]
[10, 9, 1].sort() // [1, 10, 9] lexicographic!
[10, 9, 1].sort((a, b) => a - b) // [1, 9, 10]
Use Object.freeze to shallow-freeze an object and Object.seal to prevent add/remove while allowing writes. Object.groupBy (ES2024) and Map.groupBy bucket items by a key.
Map instead of a plain object?ASolution
When keys are not strings/symbols (objects, functions, numbers), when you need guaranteed insertion order, when you need .size, or when you want a clean dictionary with no inherited or prototype keys. Plain objects are fine for fixed-shape records and JSON, and they serialize directly.
[10, 9, 1].sort() return [1, 10, 9]?ASolution
sort converts elements to strings and compares their UTF-16 code units by default, so "10" < "9". Pass a numeric comparator: sort((a, b) => a - b). It also mutates the array in place, so copy first if you need the original.
for...in and for...of?ASolution
for...in enumerates keys (including inherited enumerable ones) and is meant for objects. for...of iterates values using the iterable protocol and works on arrays, strings, Map, Set, and generators. For arrays use for...of or forEach; reserve for...in for objects and guard it with Object.hasOwn.
Copying: shallow, deep, and structuredClone
Assignment copies the reference, not the value: const b = a means both names point at the same object. Spreading and Object.assign make a shallow copy — a new outer container whose nested objects are still shared.
const a = { x: 1, nested: { y: 2 } }
const b = a // same reference
const c = { ...a } // new outer object, shared nested
c.nested.y = 99
console.log(a.nested.y) // 99 -- shared!
For a deep copy, the modern answer is structuredClone, which handles nested objects, arrays, Date, Map, Set, ArrayBuffer, and cycles. It cannot clone functions, DOM nodes, class prototypes, or symbols, and cloning is fault-isolated.
const deep = structuredClone(a) // fully independent, cycle-safe
The old fallback JSON.parse(JSON.stringify(x)) is a data-losing hack: it turns Date into a string, drops undefined/functions/symbols, throws on BigInt, and cannot handle cycles. Implement a manual deep clone in interviews only to show recursion and cycle handling:
function deepClone(value, seen = new WeakMap()) {
if (value === null || typeof value !== "object") return value
if (seen.has(value)) return seen.get(value) // handle cycles
const clone = Array.isArray(value) ? [] : {}
seen.set(value, clone)
for (const key of Reflect.ownKeys(value)) {
clone[key] = deepClone(value[key], seen)
}
return clone
}
ASolution
A shallow copy ({...o}, Object.assign, slice) creates a new top-level container but reuses the nested objects, so mutating a nested value is visible in both. A deep copy duplicates every nested level so the two are fully independent. Use structuredClone for the general case.
JSON.parse(JSON.stringify(obj)) a bad deep clone?ASolution
It only handles JSON data: Date becomes a string, Map/Set/undefined/functions/symbols are lost or become null, BigInt throws, and cyclic references throw. structuredClone preserves those types and handles cycles.
ASolution
Keep a WeakMap from original to clone. Before recursing, check whether the source is already in the map; if so return the stored clone, which breaks the cycle and preserves shared references. structuredClone does this internally.
Iteration, iterators, and generators
The iterable protocol defines [Symbol.iterator]() returning an iterator with a next() method that yields { value, done }. for...of, spread, destructuring, Map/Set constructors, and Promise.all all consume iterables. An iterable is not the same as an array-like ({ length, 0, 1 }); Array.from bridges both.
const iterable = {
[Symbol.iterator]() {
let i = 0
return { next: () => (i < 3 ? { value: i++, done: false } : { value: undefined, done: true }) }
},
}
;[...iterable] // [0, 1, 2]
A generator (function*) is a function that returns an iterator and can be paused at each yield. It is the easiest way to write lazy sequences and custom iterators, and yield* delegates to another iterable.
function* range(start, end) {
for (let i = start; i < end; i++) yield i
}
;[...range(1, 4)] // [1, 2, 3]
function* take(iter, n) {
let i = 0
for (const value of iter) {
if (i++ >= n) return
yield value
}
}
;[...take(range(0, Infinity), 3)] // [0, 1, 2]
Generators are lazy: nothing runs until next() is called, so range(0, Infinity) is safe when wrapped in take. They also enable cooperative scheduling and two-way communication (yield receives the value passed to next). Async generators (async function*) combine yield with await and are consumed with for await...of.
ASolution
An iterable has a [Symbol.iterator]() method that returns an iterator; an iterator has next() returning { value, done }. Arrays, strings, Map, Set, and generators are iterable. for...of and spread call the iterable protocol.
ASolution
Lazy sequences (produce values on demand, so infinite sequences work), custom iteration, and cooperatively pausing a function while keeping its local state. yield can also receive a value from next(v), enabling two-way communication, and async function* adds await for streaming async data.
The event loop
The event loop is the host’s scheduler. It runs one task at a time on the call stack; when the stack empties, it drains the entire microtask queue before picking up the next task. Microtasks are Promise.then/catch/finally, queueMicrotask, and MutationObserver. Tasks (macrotasks) are setTimeout/setInterval callbacks, I/O, UI events, and postMessage.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=3pt, minimum width=2.4cm, minimum height=0.72cm, font=\small\ttfamily, align=center},
a/.style={->, thick}]
\node[b, fill=blue!12] (stack) at (0,0) {call stack};
\node[b, fill=orange!16] (micro) at (4.4,0) {microtasks\\(Promise)};
\node[b, fill=green!14] (macro) at (8.8,0) {macrotasks\\(timers, I/O)};
\draw[a] (micro) -- node[above, font=\scriptsize] {drain all} (stack);
\draw[a] (macro) -- node[below, font=\scriptsize] {one per tick} (stack);
\draw[a] (stack) -- (micro);
\end{tikzpicture}
Predicting output is a staple interview question. Run the following in your head; the answer is surprisingly deterministic:
console.log("1")
setTimeout(() => console.log("2"), 0)
Promise.resolve().then(() => console.log("3"))
queueMicrotask(() => console.log("4"))
console.log("5")
// 1, 5, 3, 4, 2
The synchronous logs (1, 5) run first. Then the microtask queue drains in FIFO order (3, 4). Only then does the loop take the timer task (2). A setTimeout(fn, 0) does not mean “run now”; it means “queue after the current stack, and not before any microtasks”. The timer also has a minimum clamp (about 4 ms after nesting), so it is not a precise scheduler.
await adds one microtask hop per await, which is why a chain of awaits can starve rendering if it never yields to a task. Long synchronous work (a huge loop) blocks everything — timers, clicks, paint — because the stack never empties. Move heavy work to a Worker or break it into chunks.
setTimeout(fn, 0) or a resolved promise’s then?ASolution
The promise then callback. Promise callbacks are microtasks, and the event loop drains the entire microtask queue after each task and before the next macrotask. setTimeout(fn, 0) queues a macrotask that runs in a later tick.
ASolution
JavaScript has one thread. While the stack is busy, the event loop cannot process input, timers, or paint, so the page appears frozen. Offload the work to a Web Worker or chunk it with setTimeout/requestIdleCallback so the stack can empty between pieces.
ASolution
Microtasks (Promise.then, queueMicrotask, MutationObserver) are drained to completion after the current task, before anything else. Macrotasks/tasks (setTimeout, I/O, UI events) run one per event-loop iteration. That ordering is why all pending promise callbacks run before the next timer.
Promises
A Promise is a placeholder for a future value with three states: pending, then either fulfilled (with a value) or rejected (with a reason). It settles exactly once and never changes state again. then(onFulfilled, onRejected) always returns a new promise, which is what makes chaining work: returning a value fulfills the next promise, returning a promise adopts its state, and throwing rejects it.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=3pt, minimum width=2.1cm, minimum height=0.72cm, font=\small\ttfamily},
a/.style={->, thick}]
\node[b, fill=yellow!20] (p) at (0,0) {pending};
\node[b, fill=green!16] (f) at (3.6,0.9) {fulfilled};
\node[b, fill=red!14] (r) at (3.6,-0.9) {rejected};
\draw[a] (p) -- node[above, font=\scriptsize] {resolve} (f);
\draw[a] (p) -- node[below, font=\scriptsize] {reject} (r);
\node[font=\scriptsize, anchor=north] at (1.8,-1.5) {settles once, permanently};
\end{tikzpicture}
fetch("/user")
.then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status}`)
return res.json() // adopted by the next promise
})
.then((user) => console.log(user.name))
.catch((err) => console.error("failed:", err.message))
.finally(() => console.log("done"))
Key facts: .catch(fn) is .then(undefined, fn) and catches errors from earlier links, not later ones. .finally runs regardless and passes the value/error through. Errors thrown inside a then reject the returned promise, so a single .catch at the end handles the whole chain. An unhandled rejection fires the host’s unhandledrejection/unhandledRejection event.
The four static combinators are a frequent question:
| Method | Resolves when | Rejects when | Result |
|---|---|---|---|
Promise.all |
all fulfill | first rejects | array of values |
Promise.allSettled |
all settle | never | array of status objects |
Promise.race |
first settles | first settles (if it rejects) | first value/reason |
Promise.any |
first fulfills | all reject | first value / AggregateError |
Promise.all rejects on the first failure but the other promises keep running; only the returned promise is settled. Promise.allSettled never rejects and is what you want for “run all, inspect later”. Promise.any is the mirror of all for fallbacks.
const [a, b] = await Promise.all([getA(), getB()]) // parallel
const results = await Promise.allSettled([getA(), getB()]) // no early reject
ASolution
Pending, fulfilled, or rejected. It starts pending and settles exactly once, permanently — a forgotten resolve/reject after the first is ignored. then/finally attach handlers that run in a future microtask once it settles.
Promise.all and Promise.allSettled?ASolution
Promise.all rejects as soon as any input rejects (the others still run but their results are ignored). Promise.allSettled waits for every promise and returns {status: "fulfilled"|"rejected", ...} objects, so it never rejects. Use all when any failure is fatal and allSettled when you need every outcome.
.catch catch errors from promise chains that follow it?ASolution
No. .catch(fn) is .then(undefined, fn) and only handles rejections from earlier links in the chain. Errors thrown synchronously outside the chain, or in a later unlinked chain, are not caught. Put the .catch at the end, or add one to each branch.
.finally?ASolution
It runs whether the promise fulfilled or rejected, and passes the original value or reason through unchanged. If its callback returns a promise, the chain waits for it. finally cannot observe the value or reason — it takes no arguments — and whatever it returns is ignored unless it is a rejected promise or a throw.
async/await
async/await is syntactic sugar over promises. async makes a function return a promise; await pauses the async function until the promise settles, resuming as a microtask. Crucial detail: the function is paused, not the thread — the event loop keeps running.
async function load() {
try {
const res = await fetch("/user")
if (!res.ok) throw new Error(`HTTP ${res.status}`)
const user = await res.json()
return user
} catch (err) {
console.error(err) // awaits are catchable
throw err // rethrow to the caller
} finally {
console.log("done")
}
}
The biggest interview trap is accidental serialization. Independent work should run concurrently with Promise.all; sequential awaits inside a loop are \(O(n)\) round trips instead of one.
// slow: 3 sequential round trips
const a = await getA()
const b = await getB()
const c = await getC()
// fast: all three in parallel
const [a, b, c] = await Promise.all([getA(), getB(), getC()])
A for await...of loop with sequential awaits is sometimes unavoidable, but Promise.all plus map usually is not. Also remember that an async function always returns a promise, so returning a value from it does not give you the value synchronously — callers must await or .then.
At the top level of a module (ESM), you can await directly thanks to top-level await; in CommonJS or the browser console before module scope, wrap in an async IIFE.
async/await blocking?ASolution
The async function is paused at each await, but the JavaScript thread is not blocked — the event loop continues to process other tasks and microtasks. Blocking comes only from long synchronous work, not from await.
ASolution
Each await waits for the previous operation before starting the next, turning what could be parallel work into a serial chain. If the iterations are independent, collect the promises and run them with Promise.all. Await in a loop only when each step depends on the previous.
async/await and promises different?ASolution
No. async/await is syntax built on promises: async wraps the return value in a promise, and await calls .then under the hood. Anything you can write with await, you can write with .then; await just makes sequential async code read like synchronous code and unifies error handling with try/catch.
Utility patterns interviewers ask for
These show whether you understand closures, timing, and state. Implement them from the mechanism, not by memorising.
Debounce — delay until wait ms of silence. Each new call resets the timer, so only the last call in a burst fires.
function debounce(fn, wait) {
let timer
return function (...args) {
clearTimeout(timer)
timer = setTimeout(() => fn.apply(this, args), wait)
}
}
Throttle — allow at most one call per limit ms. Unlike debounce, the leading call fires, then calls within the window are dropped.
function throttle(fn, limit) {
let last = 0
return function (...args) {
const now = Date.now()
if (now - last >= limit) {
last = now
return fn.apply(this, args)
}
}
}
\begin{tikzpicture}[font=\rmfamily, x=0.5cm, y=0.5cm, >=stealth]
\draw[->, thick] (0,0) -- (18,0) node[right, font=\scriptsize] {time};
\foreach \x in {2,3,4,5,7,8,11,12,15,16}
\draw[green!60!black, thick] (\x,0) -- (\x,0.7);
\foreach \x in {2,5,8,11,16}
\draw[blue!70!black, very thick] (\x,0) -- (\x,-1.1);
\node[font=\scriptsize, anchor=west, text=green!45!black] at (18,0.7) {calls};
\node[font=\scriptsize, anchor=west, text=blue!70!black] at (18,-1.1) {throttled output};
\end{tikzpicture}
Curry — turn f(a, b, c) into f(a)(b)(c) by collecting arguments in a closure until enough are present.
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) return fn.apply(this, args)
return (...more) => curried.apply(this, args.concat(more))
}
}
const add = curry((a, b, c) => a + b + c)
add(1)(2)(3) // 6
add(1, 2)(3) // 6
Memoize — cache results keyed by arguments, using a Map. Stable serialization matters; JSON.stringify fails on functions and non-deterministic key order.
function memoize(fn) {
const cache = new Map()
return function (...args) {
const key = JSON.stringify(args)
if (cache.has(key)) return cache.get(key)
const result = fn.apply(this, args)
cache.set(key, result)
return result
}
}
Flatten — recursively join nested arrays to a given depth; depth Infinity means all levels.
function flatten(arr, depth = Infinity) {
return depth > 0
? arr.reduce((out, v) => out.concat(Array.isArray(v) ? flatten(v, depth - 1) : v), [])
: arr.slice()
}
flatten([1, [2, [3, [4]]]]) // [1, 2, 3, 4]
flatten([1, [2, [3, [4]]]], 1) // [1, 2, [3, [4]]]
ASolution
Debounce delays the call until activity stops for wait ms, so a burst produces one trailing call (reset on every event). Throttle allows at most one call per limit ms and fires on the leading edge, so a burst produces evenly spaced calls. Debounce suits search-as-you-type; throttle suits scroll and resize handlers.
ASolution
The cache key must uniquely identify the arguments; JSON.stringify is order-sensitive and drops functions/undefined, and mutable argument objects used as keys can change identity. Also, the memo wrapper must call itself (the wrapped version) to benefit from the cache at every level, not the raw inner function.
flatten without recursion?ASolution
Use an explicit stack: push the input, pop values, and if a value is an array push its elements back onto the stack; otherwise collect it. That avoids call-stack overflow on deeply nested arrays and is still linear in the total number of elements.
Polyfills: call, bind, and Promise.all
A polyfill reimplements a native feature for older environments. Interviewers use it to test this, closures, and the promise contract. Never ship hand-rolled polyfills blindly — libraries like core-js do it correctly — but being able to write them shows understanding.
Function.prototype.call temporarily attaches the function as a method of thisArg, invokes it, and removes it. The symbol key avoids clobbering a real property.
Function.prototype.myCall = function (thisArg, ...args) {
const key = Symbol("fn") // unique, no collision
const target = thisArg ?? globalThis
target[key] = this // `this` is the function being called
const result = target[key](...args)
delete target[key]
return result
}
bind returns a wrapper that remembers the context and pre-fills arguments. Returning a function also makes it usable with new, so a correct version forwards the prototype.
Function.prototype.myBind = function (thisArg, ...boundArgs) {
const fn = this
return function (...args) {
return fn.apply(thisArg, [...boundArgs, ...args])
}
}
Promise.all must reject on the first rejection, resolve in input order (not completion order), and handle an empty iterable.
function promiseAll(iterable) {
return new Promise((resolve, reject) => {
const items = [...iterable]
const results = new Array(items.length)
let remaining = items.length
if (remaining === 0) return resolve([])
items.forEach((item, i) => {
Promise.resolve(item).then((value) => {
results[i] = value // preserve input order
if (--remaining === 0) resolve(results)
}, reject) // first rejection wins
})
})
}
Symbol used as the key in the call polyfill?ASolution
A Symbol is guaranteed unique, so the temporary property cannot collide with or overwrite a real property on thisArg, even if the object has a key named like the one you would otherwise use. A string key could clobber user data; a symbol cannot.
Promise.all resolve in input order even when promises finish out of order?ASolution
Each result is written to results[i] using its original index, and the outer promise resolves only after all indices are filled. Completion order affects nothing; the returned array always mirrors the input iterable’s order.
bind need to preserve for new to work?ASolution
A bound function used with new must ignore the bound this and instead bind the freshly created object, and instanceof must still work. A complete polyfill detects new.target, creates an object whose prototype is fn.prototype, and applies the original function to it; arguments are still pre-filled.
Modules: CommonJS vs ESM
A module is a file with its own scope and an explicit public surface. The two systems differ in when they resolve and how bindings behave.
CommonJS (Node’s original system) uses require and module.exports, resolves synchronously at runtime, and copies values at require time. ESM uses static import/export, resolves asynchronously, and exposes live bindings — importers see later updates to the exporter’s variables.
// CommonJS
const { readFile } = require("fs") // sync, runtime
module.exports = { greet } // copies the value
// ESM
import { readFile } from "fs/promises" // static, hoisted binding
export function greet() {}
export default function main() {}
| CommonJS | ESM | |
|---|---|---|
| Syntax | require / module.exports |
import / export |
| Resolution | sync, runtime | async, static parse |
| Bindings | copied at require | live |
| Tree-shaking | hard | good (static analysis) |
| Top-level await | no | yes |
this at top level |
module.exports |
undefined |
ESM imports are hoisted and evaluated before the module body, and the graph is acyclic at load time (cycles are allowed but partially initialized bindings can be undefined). Dynamic import() returns a promise and is the bridge from CommonJS or for lazy loading.
if (needHeavy) {
const { heavy } = await import("./heavy.js") // code-split
heavy()
}
In Node, the file extension and package.json "type" field decide the mode: .mjs/"type": "module" is ESM, .cjs/"type": "commonjs" is CommonJS, and ESM can import a CommonJS package (its module.exports becomes the default export).
ASolution
CommonJS uses require/module.exports, resolves synchronously at runtime, and copies values when required. ESM uses static import/export, resolves asynchronously before execution, supports top-level await, enables tree-shaking, and exposes live bindings so importers observe later mutations.
ASolution
An imported name is a reference to the exporter’s binding, not a snapshot. If the exporting module reassigns the variable, importers see the new value. This is unlike CommonJS, where require copies the value at load time. (A const binding is still constant; live means it reflects the exporter’s current value, not that it can be reassigned by the importer.)
ASolution
Use dynamic import(), which returns a promise: const mod = await import("./mod.js"). It works inside functions and conditionals, enables code splitting, and is the polyglot bridge that lets CommonJS require an ESM module.
Memory management and garbage collection
Memory lives in the heap and is reclaimed by the engine’s garbage collector, which in modern engines uses mark-and-sweep. The collector starts from roots (globalThis, the current call stack, active closures, and DOM references), marks everything reachable, and frees the rest. Reachability, not reference counting, is the rule — which is why cycles are collectable and why “two objects reference each other” is not, by itself, a leak.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
r/.style={draw, thick, rounded corners=3pt, minimum width=1.9cm, minimum height=0.65cm, font=\small\ttfamily},
a/.style={->, thick}]
\node[r, fill=green!16] (root) at (0,0) {root};
\node[r, fill=blue!12] (a) at (3.0,0) {A};
\node[r, fill=blue!12] (b) at (5.4,0) {B};
\node[r, fill=red!12] (dead) at (3.0,-1.6) {C};
\draw[a] (root) -- (a); \draw[a] (a) -- (b); \draw[a] (b) -- (a);
\node[font=\scriptsize, anchor=north] at (1.5,-0.55) {reachable};
\node[font=\scriptsize, anchor=north] at (3.0,-2.25) {unreachable: swept};
\end{tikzpicture}
Common leaks: accidental globals (missing let/const creates a property on globalThis), timers and intervals that are never cleared, event listeners that are never removed, closures that capture large objects, and detached DOM nodes still referenced from a variable. WeakMap and WeakSet hold weak references: if the only reference to a key is the WeakMap, the entry disappears with it, making them ideal for attaching metadata to objects.
let cache = new WeakMap() // entries vanish with their keys
function track(node) {
cache.set(node, { seen: Date.now() })
}
// when `node` is removed and unreferenced, its cache entry is collected
Use the Performance/Memory panels in DevTools, take heap snapshots, and look for detached nodes and growing retained size. There is no delete for a reachability leak — you must drop the reference.
ASolution
The engine uses mark-and-sweep (with generational and incremental refinements): starting from roots such as the global object, the call stack, and active closures, it marks reachable objects and frees the unmarked ones. Because reachability is transitive, reference cycles are collected.
ASolution
An object the program can no longer use but that is still reachable — for example, a detached DOM node held in a variable, a setInterval never cleared, an event listener never removed, or a long-lived closure over a large object. The collector cannot help because a live reference remains.
WeakMap?ASolution
To attach metadata to objects without preventing their collection, to cache computed values keyed by an object, and to store private data in a module. Keys must be objects, entries are not enumerable, and an entry disappears automatically when its key becomes unreachable.
Error handling
throw accepts any value, but always throw Error (or a subclass) because error objects carry a message and a stack trace. Built-in types include Error, TypeError, RangeError, SyntaxError, ReferenceError, and AggregateError (from Promise.any).
class ValidationError extends Error {
constructor(field, message) {
super(message)
this.name = "ValidationError"
this.field = field
}
}
try {
risky()
} catch (err) {
if (err instanceof ValidationError) console.log(err.field)
else throw err // do not swallow unknown errors
} finally {
cleanup() // always runs
}
catch, finally, and throw work with await too: a rejected promise inside an async function becomes a thrown exception at the await. A function that only finallys and returns swallows the original error, so do not return from finally. Unhandled async failures surface through unhandledrejection (browsers) or unhandledRejection (Node), which is a good place for logging, not recovery.
Distinguish operational errors (bad input, network failure — handle them) from programmer errors (null dereference, wrong type — fail loudly and fix the code). Error.cause (ES2022) preserves the original error when wrapping and rethrowing.
try {
await save(data)
} catch (err) {
throw new Error("save failed", { cause: err })
}
Error instead of a string?ASolution
Error objects carry a message and a stack trace, integrate with instanceof, and can be extended with custom fields. A thrown string loses the stack, cannot be reliably distinguished from other strings, and is considered bad practice.
finally change the outcome?ASolution
finally runs after try/catch regardless of result, but if it returns a value or throws, it overrides the try/catch outcome — a common bug that hides the real error. Use finally for cleanup only.
async functions?ASolution
A throw or rejection inside then rejects the returned promise, propagating to the next rejection handler (.catch or a try/catch around await). If no handler exists, it becomes an unhandled rejection. That is why a single .catch at the end of a chain covers all earlier links.
Rapid-fire round
Short answers to the questions that come up again and again.
??vs||: nullish coalescing only falls back fornull/undefined;||falls back for any falsy value, so0 || 5is5but0 ?? 5is0.?.optional chaining: short-circuits toundefinedwhen the left side isnull/undefined, instead of throwing.- Spread vs rest: same
...token; spread expands an iterable in a call/array/object literal, rest collects remaining items into an array. Object.freezedepth: shallow; nested objects remain mutable unless frozen recursively.new.target: inside a constructor it is the constructor when called withnew, otherwiseundefined; used to block calls withoutnew.- IIFE:
(function(){ ... })()or(() => { ... })()creates a private scope; mostly replaced by block scope and modules. delete: removes an object property (or array element leaving a hole), but cannot delete a variable or aconst.label:outer: for (...) { break outer }breaks an outer loop; rarely used.with: deprecated, forbidden in strict mode, makes scope ambiguous.- Proxy and Reflect:
new Proxy(target, handler)intercepts operations (get,set,has);Reflectprovides the default behaviour for those traps. Symbol: a unique, non-string property key, useful for protocol hooks and avoiding name collisions.thisin arrow: lexical, fixed at definition, cannot be rebound withbind.0.1 + 0.2 !== 0.3: binary floating point; compare with a tolerance or useDecimal/BigInt.
?? and ||?ASolution
|| returns the right operand for any falsy left value (0, "", false, NaN), while ?? only does so for null and undefined. Use ?? when 0 or "" are valid values. Mixing ?? with || or && without parentheses is a syntax error.
Proxy used for?ASolution
To intercept fundamental operations on an object — property get/set, in, iteration, function calls — via handler traps, with Reflect forwarding to default behaviour. Uses include validation, observability, reactive frameworks, and virtual objects, at a performance cost.
Pitfalls
- Floating-point equality.
0.1 + 0.2 !== 0.3; compare with a tolerance, and never store money in afloat. thislost on extraction.const f = obj.m; f()is default-bound; bind or call through the object.varclosures in loops. One shared binding; useletfor a fresh binding per iteration.- Accidental globals. An undeclared assignment in sloppy mode creates a global; write ES modules and
"use strict". ==coercion.[] == falseistrue; use===, except forx == null.- Mutating what you think you copied.
{ ...o }andsliceare shallow; usestructuredClonefor depth. JSON.parse(JSON.stringify(x))as a clone. Loses dates,Map/Set,undefined, functions, and throws on cycles.- Serial
awaitin loops. UsePromise.allfor independent work;for awaitonly when steps depend on order. setTimeout(fn, 0)is not immediate. Microtasks run first, and timers are clamped; do not use it as a precise scheduler.- Missing
sortcomparator. Default sort is lexicographic and mutates;[10, 9, 1].sort()is wrong. - Prototype pollution. Merging untrusted objects with
__proto__can corrupt every object; useObject.create(null)or validate keys. - Blocking the event loop. A long synchronous loop freezes the UI; offload to a Worker or chunk the work.
- Swallowing errors. A
finallythat returns, or a barecatch {}, hides real failures. - Leaking listeners and timers. Always
removeEventListener/clearIntervalin cleanup. lengthas a curry arity shortcut.fn.lengthignores default and rest parameters, socurrycan over- or under-collect.
Why does this change when you extract a method, and how do closures and the event loop explain the rest of JavaScript’s surprises?
ASolution
A method’s this is chosen by the call site (implicit binding), so extracting it turns the call into a default-bound one — fix with bind or call through the object. Closures capture an outer lexical environment by reference, which is why var loop callbacks share one value while let gives each its own. The event loop runs synchronous code first, then drains all microtasks, then one macrotask, which is why promises beat setTimeout. Together, these three models explain coercion, scope, inheritance, and async ordering.