JavaScript Interview Questions
This page is a concentrated reference for JavaScript interviews. It covers the language features that interviewers consistently test — not because they are obscure, but because understanding them reveals whether a candidate truly knows how JavaScript works under the hood. Each question includes a clear explanation, code examples, and common follow-ups.
How to use this page
Questions are grouped by the level at which they are usually asked, and by topic inside each level:
| Part | Level | Topics |
|---|---|---|
| Part 1 | Junior | Types and coercion, scope and hoisting, closures, this, copying |
| Part 2 | Senior | Prototypes and classes, execution context, the event loop, promises, generators, modules |
| Part 3 | Staff | Memory and GC, WeakRef, Proxy/Reflect, ES2023–ES2025 features, shipping strategy |
| Part 4 | All levels | debounce, throttle, memoize, promise combinators, deep clone, bind, curry, EventEmitter, LRU, flatten |
| Part 5 | All levels | "What does this print?" puzzles with explanations |
Every question follows the same shape: the answer (with enough depth to survive a follow-up), a runnable example, the common wrong answer or trap, and the follow-up an interviewer asks next. Every printed output on this page was checked with Node.js 22 (and Node.js 24 for the ES2025 features that 22 lacks). Run snippets as .mjs files unless the text says otherwise — module code is strict mode, which changes this in a few puzzles.
What interviewers are actually grading
At junior level: can you predict what code does? At senior level: can you explain why, in terms of the spec's mechanisms (the job queue, [[Prototype]], environment records)? At staff level: can you reason about trade-offs — memory, ordering guarantees, API design, compatibility — and say what you would do in production?
Part 1: Junior
Types and Coercion
Q: What types does JavaScript have, and what does typeof return for each?
JavaScript has seven primitive types — undefined, null, boolean, number, bigint, string, symbol — and one non-primitive type, object. Functions and arrays are objects. Primitives are immutable and compared by value; objects are compared by reference.
typeof is a lookup table with two historical quirks: typeof null is 'object', and functions get their own answer, 'function', even though they are objects.
console.log(typeof undefined); // 'undefined'
console.log(typeof null); // 'object' <- the famous bug
console.log(typeof true); // 'boolean'
console.log(typeof 42); // 'number'
console.log(typeof NaN); // 'number'
console.log(typeof 10n); // 'bigint'
console.log(typeof 'hi'); // 'string'
console.log(typeof Symbol()); // 'symbol'
console.log(typeof {}); // 'object'
console.log(typeof []); // 'object' -> use Array.isArray
console.log(typeof class {}); // 'function'
console.log(typeof undeclaredVariable); // 'undefined' — no ReferenceError
Primitives still have methods ('abc'.toUpperCase()) because the engine temporarily wraps them in String/Number/Boolean objects ("autoboxing"). That is also why assigning a property to a primitive silently does nothing in sloppy mode and throws in strict mode.
Common wrong answer: "Arrays have type array" or "null is its own type so typeof says 'null'". Also: "everything in JavaScript is an object" — primitives are not objects.
Follow-up: How do you reliably detect an array, null, or a plain object? Array.isArray(x), x === null, and Object.prototype.toString.call(x) === '[object Object]' (or check Object.getPrototypeOf(x) === Object.prototype || === null). instanceof Array fails across realms (iframes, vm contexts) because each realm has its own Array.
Q: == vs ===
== performs type coercion before comparison. === checks both type and value without coercion.
// Surprising coercion results
0 == '' // true — both coerce to 0
0 == '0' // true
'' == '0' // false — string comparison
false == '0' // true — false → 0, '0' → 0
null == undefined // true — special rule
NaN == NaN // false — NaN is not equal to anything
// Always use ===
0 === '' // false
0 === '0' // false
null === undefined // false
The == algorithm (IsLooselyEqual in the spec) in plain words: if the types match, behave like ===. null and undefined equal each other and nothing else. Booleans are converted to numbers first. A string compared with a number is converted to a number. An object compared with a primitive is converted with ToPrimitive (valueOf, then toString). That is why [] == ![] is true: ![] is false → 0, and [] → '' → 0.
There is a third equality, Object.is, used by useState, Map keys (SameValueZero, a close cousin) and Array.prototype.includes:
console.log(NaN === NaN, Object.is(NaN, NaN)); // false true
console.log(0 === -0, Object.is(0, -0)); // true false
console.log([NaN].includes(NaN), [NaN].indexOf(NaN)); // true -1
Avoid == in Production Code
The only acceptable use of == is value == null which checks for both null and undefined. For everything else, use ===. ESLint's eqeqeq rule enforces this.
Common wrong answer: "== compares values and === compares types." Both compare values; === simply refuses to convert. Also wrong: "=== is faster" — any difference is negligible; correctness is the reason.
Follow-up: Why is indexOf(NaN) -1 but includes(NaN) true? indexOf uses strict equality; includes uses SameValueZero, which treats NaN as equal to itself.
Q: What does [] + {} evaluate to, and why?
The + operator first converts both operands with ToPrimitive. For plain objects and arrays that means calling valueOf() (which returns the object itself, so it is ignored) and then toString(). If either result is a string, + concatenates; otherwise it adds numerically. Every other arithmetic operator (-, *, /) always converts to number.
console.log([] + []); // '' both become ''
console.log([] + {}); // '[object Object]'
console.log([1, 2] + [3]); // '1,23'
console.log(1 + '2' - 1); // 11 ('12' then 12 - 1)
console.log('3' * '4'); // 12
console.log(true + 1); // 2
console.log(null + 1); // 1 null -> 0
console.log(undefined + 1); // NaN undefined -> NaN
console.log('b' + 'a' + +'a' + 'a'); // 'baNaNa'
You can control the conversion with Symbol.toPrimitive, which receives a hint of 'number', 'string' or 'default':
const price = {
[Symbol.toPrimitive](hint) {
return hint === 'string' ? '$42.00' : 42;
},
};
console.log(`${price}`); // '$42.00'
console.log(price * 2); // 84
console.log(price + 1); // 43 ('default' hint)
Common wrong answer: "{} + [] is '[object Object]' too." Typed at the start of a REPL line, {} is parsed as an empty block, so the expression is +[] → 0. Inside an expression (console.log({} + [])) it is '[object Object]'. Knowing the parsing ambiguity is the signal.
Follow-up: What does Date do differently? Date objects prefer the string hint under + (new Date() + 1 concatenates), the one built-in whose default hint behaves like 'string'.
Q: Why is 0.1 + 0.2 !== 0.3, and how do you compare floating-point numbers?
All JavaScript numbers are IEEE 754 double-precision floats: 52 bits of fraction. 0.1 and 0.2 have no exact binary representation (just as 1/3 has none in decimal), so their sum is 0.30000000000000004. Integers are exact only up to Number.MAX_SAFE_INTEGER (2^53 − 1); beyond that use BigInt.
console.log(0.1 + 0.2); // 0.30000000000000004
const nearlyEqual = (a, b, rel = 1e-9) =>
Math.abs(a - b) <= rel * Math.max(Math.abs(a), Math.abs(b));
console.log(nearlyEqual(0.1 + 0.2, 0.3)); // true
console.log(2 ** 53 === 2 ** 53 + 1); // true — precision lost
console.log(2n ** 53n === 2n ** 53n + 1n); // false — BigInt is exact
// Money: store integer cents, or use a decimal library
console.log((1999 + 1) / 100); // 20
Common wrong answer: "Use Math.abs(a - b) < Number.EPSILON." That works near 1 but fails for large numbers (where the gap between adjacent doubles exceeds EPSILON) and is too loose near 0. A relative tolerance is the robust answer.
Follow-up: What is NaN and how do you test for it? NaN is the only value not equal to itself. Number.isNaN(x) checks for NaN without coercion; the global isNaN('abc') coerces first and returns true for non-numeric strings.
Q: null vs undefined, and || vs ??
undefined means "no value was ever assigned" — missing properties, missing arguments, functions without return. null is an intentional "empty" that a programmer assigns. JSON has null but no undefined (JSON.stringify({a: undefined}) drops the key).
|| returns the right side when the left is falsy (false, 0, -0, 0n, '', null, undefined, NaN). ?? returns the right side only when the left is nullish (null or undefined). Optional chaining ?. short-circuits to undefined when the left side is nullish.
function configure(opts = {}) {
const retries = opts.retries || 3; // BUG: retries: 0 becomes 3
const timeout = opts.timeout ?? 1000; // correct: 0 stays 0
return { retries, timeout };
}
console.log(configure({ retries: 0, timeout: 0 })); // { retries: 3, timeout: 0 }
console.log(0 || 'a', 0 ?? 'a'); // 'a' 0
console.log(null ?? undefined ?? 0); // 0
const user = { profile: null };
console.log(user.profile?.name); // undefined, no TypeError
console.log(user.getName?.()); // undefined — optional call
Default parameters (function f(x = 5)) apply only when the argument is undefined, not null — the same rule as ?? minus null.
Common wrong answer: "?? and || are interchangeable." They differ for every falsy non-nullish value, which is exactly where configuration bugs live (port 0, empty string titles, false flags).
Follow-up: Can you mix ?? with || without parentheses? No — a || b ?? c is a SyntaxError by design; you must write (a || b) ?? c.
Scope, Hoisting and the Temporal Dead Zone
Q: What is hoisting?
Hoisting is JavaScript's behavior of moving declarations to the top of their scope during the compilation phase. Only the declaration is hoisted, not the initialization.
// What you write:
console.log(x); // undefined (not ReferenceError)
var x = 5;
// What the engine sees:
var x; // declaration hoisted
console.log(x); // undefined
x = 5; // assignment stays in place
Clarification (2026-11-09): "Moving declarations to the top" is a mental model — nothing is physically moved. What really happens is that when a scope is entered, the engine creates its environment record and instantiates every binding declared in it before running any code.
varbindings are initialized toundefined, function declarations are initialized to the whole function, andlet/const/classbindings are created but left uninitialized (the TDZ).
Function declarations are hoisted with their body, which is why you can call them before they appear. Function expressions follow the rules of the variable they are assigned to:
console.log(typeof hoisted, typeof notHoisted); // 'function' 'undefined'
function hoisted() {}
var notHoisted = function () {};
Common wrong answer: "Only var is hoisted." All declarations are hoisted; they differ in how they are initialized.
Follow-up: What does this print? — the shadowing variant:
var x = 1;
function outer() {
console.log(x); // undefined — the local var x is hoisted and shadows the global
var x = 2;
}
outer();
Q: var vs let vs const
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function | Block | Block |
| Hoisted | Yes (initialized to undefined) | Yes (not initialized — TDZ) | Yes (not initialized — TDZ) |
| Re-declaration | Allowed | Error | Error |
| Re-assignment | Allowed | Allowed | Error |
| Global property | var x creates window.x | No | No |
const makes the binding immutable, not the value: const arr = []; arr.push(1) is fine. Use Object.freeze (shallow) for value immutability. The practical default in modern code: const everywhere, let when you reassign, var never.
const settings = { theme: 'dark' };
settings.theme = 'light'; // allowed — mutation
try { settings = {}; } catch (e) { console.log(e.name); } // TypeError
const frozen = Object.freeze({ nested: { a: 1 } });
frozen.nested.a = 2; // allowed — freeze is shallow
console.log(frozen.nested.a); // 2
Common wrong answer: "const objects can't be changed."
Follow-up: Why does let in a for loop fix the closure bug? Each iteration gets a fresh binding, copied from the previous iteration's value (see the loop question below).
Q: What is the Temporal Dead Zone?
The TDZ is the region between entering a block and the let/const declaration being reached. Accessing the variable in the TDZ throws a ReferenceError.
{
// TDZ starts here for `name`
console.log(name); // ReferenceError: Cannot access 'name' before initialization
let name = 'Alice'; // TDZ ends here
console.log(name); // 'Alice'
}
Interview Signal
If a candidate says "let and const are not hoisted," they are wrong. They are hoisted, but they are not initialized. The TDZ prevents access before the declaration. This distinction matters.
The TDZ is temporal, not positional — a function defined above the declaration can reference the variable as long as it is called after initialization:
function read() { return value; } // fine to define
// read(); // would throw: still in TDZ
let value = 42;
console.log(read()); // 42
Common wrong answer: "TDZ errors are about code position." It is about execution time. A related trap: typeof x throws inside the TDZ, even though typeof on an undeclared variable is safe.
Follow-up: Why did the language add a TDZ instead of initializing to undefined? So that const never observably has two values, and to catch use-before-define bugs early.
Q: Function declarations vs function expressions vs arrow functions
Declaration function f(){} | Expression const f = function(){} | Arrow const f = () => {} | |
|---|---|---|---|
| Hoisted with body | Yes | No (follows const rules) | No |
Own this | Yes (dynamic) | Yes (dynamic) | No (lexical) |
arguments | Yes | Yes | No |
Usable with new | Yes | Yes | No — TypeError |
Has prototype | Yes | Yes | No |
const add = (a, b) => a + b;
console.log(add(2, 3)); // 5
try { new add(); } catch (e) { console.log(e.message); } // add is not a constructor
const named = function fact(n) { return n <= 1 ? 1 : n * fact(n - 1); };
console.log(named(5)); // 120 — the name is visible inside only
Common wrong answer: "Arrow functions are just shorter syntax." They differ semantically in this, arguments, new, and prototype.
Follow-up: When must you NOT use an arrow function? Object methods that use this, prototype methods, constructors, and DOM handlers that rely on this === event.currentTarget.
Closures
Q: What is a closure? Give a practical example.
A closure is a function that retains access to its lexical scope even when the function is executed outside that scope. Every function in JavaScript forms a closure, but we typically use the term when an inner function references variables from an outer function after the outer function has returned.
function createCounter(initialValue = 0) {
let count = initialValue; // closed over by the returned object
return {
increment() { return ++count; },
decrement() { return --count; },
getCount() { return count; },
};
}
const counter = createCounter(10);
console.log(counter.increment()); // 11
console.log(counter.increment()); // 12
console.log(counter.getCount()); // 12
// `count` is not accessible directly — it's private via closure
Mechanically, each function object stores a reference to the environment record in which it was created (the spec's [[Environment]] slot). When it runs, variable lookup walks from its own environment outward through those links. Closures capture bindings, not values — if the variable changes later, the closure sees the new value.
Common wrong answer: "A closure copies the variables when the function is created." It holds a live reference to the binding — which is exactly why the var loop bug below happens.
Follow-up: Do closures cause memory leaks? They keep their environment alive as long as the function is reachable. V8 only retains variables that some inner function actually references, but all closures created in the same scope share one context object — so one long-lived closure can keep a big variable alive that only a sibling closure used.
Q: What will this loop print, and how do you fix it?
// Classic closure bug
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// Prints: 3, 3, 3 — because `var` is function-scoped
Fix 1 — use let (block-scoped, creates new binding per iteration):
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// Prints: 0, 1, 2
Fix 2 — IIFE (creates a new scope per iteration):
for (var i = 0; i < 3; i++) {
(function (j) {
setTimeout(() => console.log(j), 100);
})(i);
}
There is only one var i for the whole function; by the time any callback runs, the loop has finished and i is 3. With let, the spec's CreatePerIterationEnvironment creates a fresh copy of i for each iteration. Fix 3 is setTimeout(console.log, 100, i), which passes the current value as an argument.
Common wrong answer: "It prints 0, 1, 2 because setTimeout captures i." Or "it prints 3 because the timeout is 100ms" — the delay is irrelevant; setTimeout(..., 0) prints the same.
Follow-up: Does the same bug happen without timers? Yes — const fns = []; for (var i = 0; i < 3; i++) fns.push(() => i); fns.map(f => f()) returns [3, 3, 3].
Q: Real-world closure — rate limiter
function createRateLimiter(maxCalls, windowMs) {
const timestamps = [];
return function (...args) {
const now = Date.now();
// Remove timestamps outside the window
while (timestamps.length && timestamps[0] <= now - windowMs) {
timestamps.shift();
}
if (timestamps.length >= maxCalls) {
throw new Error('Rate limit exceeded');
}
timestamps.push(now);
return true;
};
}
const limiter = createRateLimiter(5, 1000); // 5 calls per second
This is a sliding-window log: it stores one timestamp per accepted call, so memory is O(maxCalls) and the check is exact. The closure makes timestamps private state that only the returned function can touch.
Common wrong answer: Using a fixed window (count reset every second by setInterval). It allows bursts of 2 × max at window boundaries, and the interval keeps the process alive.
Follow-up: How would you rate-limit across multiple server instances? Closures are per-process. Move the state to Redis (a sorted set per key, or an atomic token-bucket Lua script). Also note shift() is O(n) — a ring buffer or token bucket is O(1).
this Binding
Q: Explain the four rules of this binding.
graph TD
A["How was the function called?"]
B["new keyword?<br/>this = new object"]
C["call/apply/bind?<br/>this = specified object"]
D["obj.method()?<br/>this = obj"]
E["plain call?<br/>this = undefined (strict)<br/>this = window (sloppy)"]
F["Arrow function?<br/>this = enclosing lexical this"]
A --> B
A --> C
A --> D
A --> E
A --> F
style B fill:#059669,color:#fff
style C fill:#0891b2,color:#fff
style D fill:#d97706,color:#fff
style E fill:#dc2626,color:#fff
style F fill:#7c3aed,color:#fff
// 1. Default binding
function showThis() { console.log(this); }
showThis(); // window (browser, sloppy) or undefined (strict)
// 2. Implicit binding
const obj = { name: 'Alice', greet() { return this.name; } };
obj.greet(); // 'Alice' — this = obj
// 3. Explicit binding
function greet() { return this.name; }
greet.call({ name: 'Bob' }); // 'Bob'
greet.apply({ name: 'Carol' }); // 'Carol'
const bound = greet.bind({ name: 'Dave' });
bound(); // 'Dave'
// 4. new binding
function Person(name) { this.name = name; }
const p = new Person('Eve'); // this = newly created object
// 5. Arrow functions — lexical this
const team = {
name: 'Engineering',
members: ['Alice', 'Bob'],
list() {
// Arrow inherits `this` from list()'s scope
return this.members.map(m => `${m} is in ${this.name}`);
},
};
Clarification (2026-11-09): In sloppy mode the default binding is the global object —
windowin browsers butglobalThisin Node.js. ES modules and classes are always strict, so in modern code a plain call almost always givesundefined.
Precedence when rules conflict: new > explicit (bind) > implicit (obj.method()) > default. bind can't be overridden by a later call, but new on a bound function ignores the bound this (see the bind implementation in Part 4).
Common wrong answer: "this refers to the function itself" or "to where the function was defined." For normal functions it is determined by the call site; only arrows are lexical.
Follow-up: What is this inside a callback passed to addEventListener? The element (event.currentTarget) for a normal function; the enclosing this for an arrow.
Q: Classic this trap
const user = {
name: 'Alice',
greet() { return `Hi, I'm ${this.name}`; },
};
const greetFn = user.greet; // method extraction — loses implicit binding
greetFn(); // "Hi, I'm undefined" — default binding
// Fix: bind it
const boundGreet = user.greet.bind(user);
boundGreet(); // "Hi, I'm Alice"
Clarification (2026-11-09): The
"Hi, I'm undefined"result is sloppy-mode behaviour (thisis the global object, which has noname). In strict mode or an ES module,thisisundefinedandthis.namethrows aTypeError.
The same trap appears whenever a method is passed as a value: setTimeout(user.greet, 0), array.map(obj.method), promise.then(obj.method), or destructuring const { greet } = user. Class fields with arrow functions avoid it at the cost of one function per instance:
class Button {
label = 'ok';
handler = () => this.label; // bound per instance
method() { return this?.label; } // shared on the prototype
}
const { handler, method } = new Button();
console.log(handler(), method()); // 'ok' undefined
Common wrong answer: "Arrow class fields are free." Each instance gets its own copy of the function (more memory, not on the prototype, not overridable via super).
Follow-up: How do React class components deal with this? Historically this.handleClick = this.handleClick.bind(this) in the constructor or arrow class fields — one reason hooks were introduced.
Copying and Mutation
Q: Shallow copy vs deep copy — and what does structuredClone do?
A shallow copy duplicates the top level; nested objects are shared. Spread ({...obj}, [...arr]), Object.assign, Array.from and slice are all shallow. A deep copy duplicates every level.
structuredClone (in browsers and Node 17+) performs a real deep copy using the structured clone algorithm: it handles cycles, Map, Set, Date, RegExp, typed arrays, Errors and more. It cannot clone functions, DOM nodes, or class prototypes (instances come back as plain objects), and it drops getters/setters and property descriptors.
const original = { tags: ['a'], when: new Date(0), meta: new Map([['k', 1]]) };
const shallow = { ...original };
shallow.tags.push('b');
console.log(original.tags); // ['a', 'b'] — shared
const deep = structuredClone(original);
deep.tags.push('c');
console.log(original.tags, deep.when instanceof Date); // ['a', 'b'] true
try { structuredClone({ fn() {} }); } catch (e) { console.log(e.name); } // DataCloneError
console.log(JSON.parse(JSON.stringify({ d: new Date(0), u: undefined })));
// { d: '1970-01-01T00:00:00.000Z' } — Date became a string, undefined dropped
Common wrong answer: "JSON.parse(JSON.stringify(x)) is a deep clone." It loses Date (becomes string), undefined, functions, Map/Set (become {}), Infinity/NaN (become null), and throws on cycles and BigInt.
Follow-up: Write a deep clone yourself — see Part 4.
Q: Which array methods mutate, and what are the ES2023 non-mutating alternatives?
Mutating: push, pop, shift, unshift, splice, sort, reverse, fill, copyWithin. ES2023 added copying versions: toSorted, toReversed, toSpliced, and with(index, value). These matter in React/Redux, where mutating state in place breaks change detection.
Also, sort() with no comparator converts elements to strings and sorts by UTF-16 code units:
console.log([10, 1, 2].sort()); // [1, 10, 2] — string order!
console.log([10, 1, 2].sort((a, b) => a - b)); // [1, 2, 10]
const scores = [3, 1, 2];
const sorted = scores.toSorted();
console.log(scores, sorted); // [3, 1, 2] [1, 2, 3]
console.log([1, 2, 3].with(1, 9)); // [1, 9, 3]
console.log([1, 2, 3, 4].findLast(x => x % 2), [1, 2, 3].at(-1)); // 3 3
Array.prototype.sort has been required to be stable since ES2019, so sorting by one key preserves the previous order among ties.
Common wrong answer: "sort() sorts numbers numerically." And "const sorted = arr.sort() gives a new array" — it returns the same array, sorted in place.
Follow-up: What does ['1', '7', '11'].map(parseInt) return? [1, NaN, 3] — map passes (value, index), so the calls are parseInt('1', 0), parseInt('7', 1) (radix 1 is invalid → NaN), and parseInt('11', 2) → 3.
Part 2: Senior
Prototypes and Classes
Q: How does prototypal inheritance work?
Every JavaScript object has an internal [[Prototype]] link to another object. When you access a property that does not exist on the object, the engine walks up the prototype chain until it finds the property or reaches null.
graph LR
obj["myObj<br/>{name: 'Alice'}"] -->|"__proto__"| proto["Person.prototype<br/>{greet()}"]
proto -->|"__proto__"| op["Object.prototype<br/>{toString(), hasOwnProperty()}"]
op -->|"__proto__"| null_["null"]
Reads walk the chain; writes do not — assigning obj.x = 1 creates an own property on obj (shadowing the prototype's x) unless the prototype has a setter or a non-writable x. Methods are shared through the prototype, so a thousand instances share one greet function.
const base = { greet() { return `hi from ${this.name}`; }, kind: 'base' };
const child = Object.create(base);
child.name = 'child';
console.log(child.greet()); // 'hi from child' — this is the receiver
child.kind = 'child'; // shadows, does not modify base
console.log(base.kind, child.kind); // 'base' 'child'
console.log(Object.hasOwn(child, 'greet')); // false
console.log(Object.getPrototypeOf(child) === base); // true
Common wrong answer: "__proto__ and prototype are the same thing." prototype is a property on constructor functions — the object that becomes [[Prototype]] of instances made with new. __proto__ is a legacy accessor for an object's own [[Prototype]]; prefer Object.getPrototypeOf/Object.setPrototypeOf.
Follow-up: Why is Object.setPrototypeOf on hot objects discouraged? Changing an object's prototype after creation invalidates the engine's hidden-class/inline-cache optimizations for that object; set the prototype at creation with Object.create or class.
Q: Object.create vs class syntax
// Object.create — direct prototype linkage
const animal = {
speak() { return `${this.name} makes a sound`; }
};
const dog = Object.create(animal);
dog.name = 'Rex';
dog.bark = function () { return `${this.name} barks`; };
console.log(dog.speak()); // "Rex makes a sound" — found via prototype chain
console.log(dog.bark()); // "Rex barks"
// ES6 class — syntactic sugar over prototypal inheritance
class Animal {
constructor(name) { this.name = name; }
speak() { return `${this.name} makes a sound`; }
}
class Dog extends Animal {
bark() { return `${this.name} barks`; }
}
const rex = new Dog('Rex');
// Under the hood: rex.__proto__ === Dog.prototype
// Dog.prototype.__proto__ === Animal.prototype
Classes Are Not Classical Inheritance
ES6 class is syntactic sugar. There are no "classes" in the Java/C++ sense. extends sets up a prototype chain. Understanding this avoids confusion with super, static, and method resolution.
"Sugar" is slightly understated — classes have real semantic differences from constructor functions: class bodies are strict mode; classes are in the TDZ until declared; calling a class without new throws; methods are non-enumerable; and extends also links the constructors themselves (Object.getPrototypeOf(Dog) === Animal), so static methods inherit. In a derived class you must call super() before touching this, because the base constructor allocates the object.
Common wrong answer: "Classes copy methods into instances like in Java." Methods live on Dog.prototype; instances only hold fields.
Follow-up: Why does extends Array or extends Error work with classes but was painful with ES5 functions? Because with class, the base constructor creates the exotic object (a real array with magic length, or an error with a stack), and new.target makes its prototype Dog.prototype. ES5's Array.call(this) couldn't do that.
Q: What does instanceof do?
instanceof checks whether an object has a given constructor's prototype anywhere in its prototype chain:
rex instanceof Dog; // true — Dog.prototype is in rex's chain
rex instanceof Animal; // true — Animal.prototype is also in the chain
rex instanceof Object; // true — Object.prototype is at the top
Clarification (2026-11-09): That is the default behaviour. If the right-hand side defines
Symbol.hasInstance,instanceofcalls it instead, so a class can customize the check.
class Even {
static [Symbol.hasInstance](n) { return Number.isInteger(n) && n % 2 === 0; }
}
console.log(2 instanceof Even, 3 instanceof Even); // true false
const bare = Object.create(null);
console.log(bare instanceof Object); // false — no Object.prototype in chain
Common wrong answer: "instanceof checks which constructor created the object." It checks the current prototype chain. Reassign Dog.prototype after creating rex and rex instanceof Dog becomes false.
Follow-up: Why can instanceof Array lie? Values from another realm (iframe, vm.runInNewContext, a worker's structured clone) have a different Array.prototype. Use Array.isArray, or brand checks such as #field in obj for your own classes.
Q: What exactly does new do? Implement it.
new F(...args) performs four steps: create an object whose [[Prototype]] is F.prototype; call F with this bound to that object; if F returns an object (or function), use that; otherwise return the new object.
function myNew(Ctor, ...args) {
const obj = Object.create(Ctor.prototype);
const result = Ctor.apply(obj, args);
return result !== null && (typeof result === 'object' || typeof result === 'function')
? result
: obj;
}
function Point(x, y) { this.x = x; this.y = y; }
Point.prototype.len = function () { return Math.hypot(this.x, this.y); };
const p = myNew(Point, 3, 4);
console.log(p instanceof Point, p.len()); // true 5
Common wrong answer: Forgetting step four — a constructor that returns an object overrides this, and returning a primitive is ignored.
Follow-up: Can myNew handle class constructors? No — classes throw when called without new. You'd use Reflect.construct(Ctor, args), which also sets new.target correctly.
Q: How do you make data private — #fields, closures, or WeakMap?
Three generations of privacy:
- Closures (factory functions): true privacy, but every instance gets its own copy of every method.
- WeakMap keyed by instance (the ES2015-era pattern, shown in the Memory section): methods stay on the prototype, data is unreachable without the map.
#privatefields (ES2022): language-level, enforced by the engine, with#x in objbrand checks and private methods/static members.
class Account {
#balance = 0;
static #count = 0;
constructor() { Account.#count++; }
deposit(n) { if (n <= 0) throw new RangeError('positive only'); this.#balance += n; return this; }
get balance() { return this.#balance; }
static isAccount(x) { return #balance in x; } // brand check
static get count() { return Account.#count; }
}
const acct = new Account().deposit(50);
console.log(acct.balance, Account.isAccount(acct), Account.isAccount({})); // 50 true false
console.log(Object.keys(acct), JSON.stringify(acct)); // [] '{}'
Common wrong answer: "_balance is private." The underscore is a convention only. And "#fields are just non-enumerable properties" — they are not properties at all; Proxy and Reflect.ownKeys can't see them.
Follow-up: What breaks when you wrap a class with #fields in a Proxy? Methods invoked through the proxy run with this === proxy, and this.#balance throws a TypeError because the proxy doesn't have the private slot. Bind methods to the target or avoid proxies for such classes.
Scope and Execution Context
Q: What is an execution context?
Every time a function is invoked, JavaScript creates an execution context containing:
- Variable Environment —
vardeclarations, function declarations - Lexical Environment —
let/constdeclarations, block scoping thisbinding — determined by how the function was called- Outer reference — link to the parent scope (closure mechanism)
graph TD
GEC["Global Execution Context<br/>Variables: x, myFunc<br/>this: window/global"]
FEC["Function Execution Context: myFunc()<br/>Variables: y, innerFunc<br/>this: depends on call site"]
IEC["Function Execution Context: innerFunc()<br/>Variables: z<br/>this: depends on call site"]
GEC --> FEC --> IEC
Contexts are pushed onto the call stack; when a function returns, its context is popped — but its environment record survives if a closure still references it. Generators and async functions are special: their context is suspended and later resumed, which is how yield and await work without threads.
function a() { b(); }
function b() { console.log(new Error('where am I').stack.split('\n').slice(1, 3).join('\n')); }
a(); // stack trace shows b, then a — the call stack at that moment
function recurse(n) { return recurse(n + 1); }
try { recurse(0); } catch (e) { console.log(e instanceof RangeError); } // true — stack overflow
Common wrong answer: Confusing scope (lexical, decided by where code is written) with context (this, decided by how a function is called).
Follow-up: Does JavaScript have tail-call optimization? ES2015 specified proper tail calls in strict mode, but only Safari's JavaScriptCore implements them; V8 and SpiderMonkey don't. Don't rely on deep recursion — convert to a loop.
Event Loop
Q: Explain the JavaScript event loop.
JavaScript is single-threaded. The event loop is the mechanism that allows non-blocking I/O by offloading operations to the system kernel or thread pool and processing callbacks when the call stack is empty.
graph TD
CS["Call Stack<br/>(synchronous code)"]
WA["Web APIs / Node APIs<br/>(setTimeout, fetch, I/O)"]
TQ["Task Queue<br/>(macrotasks: setTimeout, setInterval)"]
MQ["Microtask Queue<br/>(Promise.then, queueMicrotask, MutationObserver)"]
EL["Event Loop"]
CS -->|"async call"| WA
WA -->|"callback ready"| TQ
CS -->|"Promise resolved"| MQ
EL -->|"stack empty? drain microtasks first"| MQ
EL -->|"then pick one macrotask"| TQ
MQ -->|"push to stack"| CS
TQ -->|"push to stack"| CS
style MQ fill:#059669,color:#fff
style TQ fill:#d97706,color:#fff
The precise algorithm (HTML spec, simplified): run one task (a macrotask — a script, a timer callback, an event handler); when the stack is empty, drain the microtask queue completely, including microtasks queued by microtasks; then, if it is time, perform a rendering step (requestAnimationFrame callbacks, style, layout, paint); repeat. The language itself (ECMAScript) only defines the job queue for promises; the host (browser or Node) defines everything else. That is why Node's loop has phases and browsers have task sources.
Common wrong answer: "JavaScript is single-threaded, so async code runs on another thread." Your callbacks always run on the one JS thread; only the waiting (network, timers, file I/O in Node's threadpool) happens elsewhere.
Follow-up: What happens if a microtask keeps scheduling microtasks? The queue never empties, so no timer, event, or render ever runs — the page freezes just as with an infinite loop. See the starvation question below.
Q: What is the output order?
console.log('1');
setTimeout(() => console.log('2'), 0);
Promise.resolve().then(() => console.log('3'));
queueMicrotask(() => console.log('4'));
console.log('5');
Answer: 1, 5, 3, 4, 2
1and5are synchronous — they execute immediately.3and4are microtasks — they run after the current synchronous code finishes but before any macrotask.2is a macrotask (setTimeout) — it runs last.
Microtasks Always Beat Macrotasks
After each macrotask completes, the engine drains the entire microtask queue before picking the next macrotask. This is why Promise.then callbacks execute before setTimeout(..., 0).
Common wrong answer: "2 comes before 3 because setTimeout was called first." Scheduling order only matters within a queue.
Follow-up: Is 3 always before 4? Yes — both are in the same FIFO microtask queue and were enqueued in that order.
Q: Worked puzzle — async/await, promises, and timers together
This is the puzzle most likely to appear on a whiteboard. Predict every line before reading the walkthrough.
console.log('script start');
setTimeout(() => console.log('timeout 1'), 0);
async function a1() {
console.log('a1 start');
await a2();
console.log('a1 end');
}
async function a2() { console.log('a2'); }
a1();
new Promise((resolve) => {
console.log('promise executor');
resolve();
}).then(() => {
console.log('then 1');
setTimeout(() => console.log('timeout 2'), 0);
}).then(() => console.log('then 2'));
queueMicrotask(() => console.log('microtask'));
console.log('script end');
Output (verified on Node 22; identical in current Chrome and Firefox):
script start
a1 start
a2
promise executor
script end
a1 end
then 1
microtask
then 2
timeout 1
timeout 2
Step by step:
| Step | What runs | Microtask queue after | Task queue after |
|---|---|---|---|
| 1 | script start (sync) | — | timeout 1 |
| 2 | a1() runs synchronously until its first await: prints a1 start; a2() runs synchronously and prints a2, returning an already-resolved promise; await schedules the continuation | a1-continuation | timeout 1 |
| 3 | The promise executor runs synchronously: promise executor; resolve() then .then registers then-1 (promise is already resolved, so it is queued immediately) | a1-cont, then 1 | timeout 1 |
| 4 | queueMicrotask | a1-cont, then 1, microtask | timeout 1 |
| 5 | script end; the script task ends, microtask checkpoint starts | ||
| 6 | a1 end, then then 1 (which schedules timeout 2 and resolves its promise, queuing then 2), then microtask, then then 2 | empty | timeout 1, timeout 2 |
| 7 | Next task: timeout 1, then next task: timeout 2 |
Key facts this tests: an async function body runs synchronously until the first await; the Promise executor runs synchronously; await on a native promise costs exactly one microtask hop (since the 2018–2019 "await optimization" in V8 and the spec); and microtasks queued during the checkpoint run in the same checkpoint.
Common wrong answer: Putting a1 end right after a2 (forgetting that await always yields, even for an already-resolved value), or putting a1 end after then 2 (the pre-2019 behaviour, where await took three ticks).
Follow-up: What changes if a2 is not async but returns a non-promise? Nothing in the order — await 'x' wraps the value in a resolved promise and still takes one microtask hop.
Q: Two promise chains — how do they interleave, and why does return Promise.resolve() in an async function cost extra ticks?
Each .then callback only enqueues the next link when it completes, so two independent chains alternate one link at a time:
Promise.resolve().then(() => console.log('A1')).then(() => console.log('A2')).then(() => console.log('A3'));
Promise.resolve().then(() => console.log('B1')).then(() => console.log('B2')).then(() => console.log('B3'));
// A1 B1 A2 B2 A3 B3
Returning a promise (a thenable) from an async function or a .then callback is slower than returning a value: the spec has to schedule a NewPromiseResolveThenableJob, which calls .then on the returned promise, which then schedules another job. That is two extra microtask hops.
async function f() { return Promise.resolve('f'); } // thenable -> 2 extra ticks
async function g() { return 'g'; } // plain value
f().then(console.log);
g().then(console.log);
Promise.resolve().then(() => console.log('t1')).then(() => console.log('t2')).then(() => console.log('t3'));
// g t1 t2 f t3
Common wrong answer: "f and g resolve at the same time because both are already resolved."
Follow-up: Does return await promise inside an async function change this? Yes — it costs one hop instead of two, and inside a try block it is required if you want the catch to see the rejection. This is why the old "return await is redundant" lint rule was relaxed.
Q: Where do rendering, requestAnimationFrame and microtask starvation fit in the browser?
After each task and its microtask checkpoint, the browser may render (typically once per display frame, ~16.7ms at 60Hz). Before style/layout/paint it runs requestAnimationFrame callbacks. So:
- Code in a microtask loop blocks rendering just like a synchronous loop.
- Splitting work with
setTimeout(fn, 0)yields to rendering between chunks (browsers clamp nested timers to ≥4ms after 5 levels). scheduler.postTask()andscheduler.yield()(Chromium; check support) give priority-aware yielding.
// Chunked work that keeps the UI responsive
async function processInChunks(items, handle, chunkSize = 500) {
for (let i = 0; i < items.length; i += chunkSize) {
items.slice(i, i + chunkSize).forEach(handle);
await new Promise((r) => setTimeout(r, 0)); // a macrotask boundary — lets the browser paint
}
}
// Starvation: this never lets a timer fire
// function starve() { Promise.resolve().then(starve); } starve();
let sum = 0;
processInChunks(Array.from({ length: 2000 }, (_, i) => i), (n) => { sum += n; })
.then(() => console.log(sum)); // 1999000
Common wrong answer: "Yield with await Promise.resolve()." That is a microtask — it never gives the browser a chance to render or handle input.
Follow-up: Where does MutationObserver fire? As a microtask. Where does requestIdleCallback fire? In idle periods after rendering, with a deadline — good for analytics, bad for anything visible.
Q: Node.js Event Loop Phases
In Node.js, the event loop has six phases:
| Phase | What Runs |
|---|---|
| Timers | setTimeout, setInterval callbacks |
| Pending callbacks | I/O callbacks deferred from previous cycle |
| Idle, prepare | Internal use only |
| Poll | Retrieve new I/O events; execute I/O callbacks |
| Check | setImmediate callbacks |
| Close callbacks | socket.on('close', ...) etc. |
// Node.js specific — order depends on context
setTimeout(() => console.log('timeout'), 0);
setImmediate(() => console.log('immediate'));
// Order is non-deterministic in the main module
// But inside an I/O callback, setImmediate always fires first
const fs = require('fs');
fs.readFile(__filename, () => {
setTimeout(() => console.log('timeout'), 0);
setImmediate(() => console.log('immediate'));
// Always prints: immediate, timeout
});
In Node, process.nextTick callbacks run before promise microtasks, and since Node 11 both queues are drained after every individual callback, not just between phases. The full treatment, with more puzzles, lives on the Node.js interview page.
Common wrong answer: "setImmediate means 'run immediately', so it beats nextTick." The names are historical accidents — nextTick is the more immediate of the two.
Follow-up: Why is setTimeout vs setImmediate non-deterministic in the main module? setTimeout(fn, 0) is really 1ms. Whether 1ms has elapsed by the time the loop first checks timers depends on process startup speed.
Promises and Async/Await
Q: Implement a basic Promise from scratch
class SimplePromise {
#state = 'pending';
#value = undefined;
#callbacks = [];
constructor(executor) {
const resolve = (value) => {
if (this.#state !== 'pending') return;
this.#state = 'fulfilled';
this.#value = value;
this.#callbacks.forEach(cb => cb.onFulfilled(value));
};
const reject = (reason) => {
if (this.#state !== 'pending') return;
this.#state = 'rejected';
this.#value = reason;
this.#callbacks.forEach(cb => cb.onRejected(reason));
};
try { executor(resolve, reject); }
catch (err) { reject(err); }
}
then(onFulfilled, onRejected) {
return new SimplePromise((resolve, reject) => {
const handle = () => {
try {
if (this.#state === 'fulfilled') {
const result = onFulfilled ? onFulfilled(this.#value) : this.#value;
resolve(result);
} else if (this.#state === 'rejected') {
if (onRejected) resolve(onRejected(this.#value));
else reject(this.#value);
}
} catch (err) { reject(err); }
};
if (this.#state === 'pending') {
this.#callbacks.push({ onFulfilled: () => handle(), onRejected: () => handle() });
} else {
queueMicrotask(handle);
}
});
}
}
Correction (2026-11-09): The version above has two spec deviations an interviewer will probe. (1) When the promise is still pending,
thencallbacks run synchronously insideresolve()instead of in a microtask, so code afterresolve()runs after the handlers. Promises/A+ requires handlers to always run asynchronously. (2)resolve(otherPromise)stores the promise itself as the value instead of adopting its state. The corrected version below fixes both and addscatch. It was tested on Node 22.
class SimplePromise {
#state = 'pending';
#value;
#callbacks = [];
constructor(executor) {
const settle = (state, value) => {
if (this.#state !== 'pending') return;
this.#state = state;
this.#value = value;
this.#callbacks.forEach((cb) => queueMicrotask(cb)); // always async
this.#callbacks = [];
};
const resolve = (value) => {
if (value && typeof value.then === 'function') { // adopt thenables
value.then(resolve, reject);
return;
}
settle('fulfilled', value);
};
const reject = (reason) => settle('rejected', reason);
try { executor(resolve, reject); } catch (err) { reject(err); }
}
then(onFulfilled, onRejected) {
return new SimplePromise((resolve, reject) => {
const handle = () => {
try {
if (this.#state === 'fulfilled') resolve(onFulfilled ? onFulfilled(this.#value) : this.#value);
else if (onRejected) resolve(onRejected(this.#value));
else reject(this.#value);
} catch (err) { reject(err); }
};
if (this.#state === 'pending') this.#callbacks.push(handle);
else queueMicrotask(handle);
});
}
catch(onRejected) { return this.then(undefined, onRejected); }
}
const order = [];
let resolveLater;
new SimplePromise((r) => { resolveLater = r; }).then((v) => order.push('then:' + v));
resolveLater(1);
order.push('sync after resolve');
setTimeout(() => console.log(order), 0); // ['sync after resolve', 'then:1']
Still missing for full A+ compliance: guarding against a thenable whose then getter throws or calls both callbacks, and rejecting with a TypeError when a promise is resolved with itself.
Common wrong answer: Calling handlers synchronously when the promise is already resolved ("it's resolved, so just call it").
Follow-up: Add finally. finally(cb) must pass the original value or reason through: then(v => Promise.resolve(cb()).then(() => v), e => Promise.resolve(cb()).then(() => { throw e; })).
Q: Promise.all vs Promise.race vs Promise.allSettled
| Method | Resolves when | Rejects when | Use case |
|---|---|---|---|
Promise.all | All promises resolve | Any one rejects | Fetch all data before rendering |
Promise.race | First promise settles | First promise rejects | Timeout pattern |
Promise.allSettled | All promises settle | Never rejects | Run independent tasks, inspect each result |
Promise.any | First promise resolves | All reject (AggregateError) | First successful response from mirrors |
Correction (2026-11-09):
Promise.racesettles the same way as whichever input settles first — it fulfils if the first to settle fulfils and rejects if the first to settle rejects. "Rejects when first promise rejects" was ambiguous: a rejection that arrives after another input has already fulfilled is ignored.
// Timeout pattern with Promise.race
function fetchWithTimeout(url, ms) {
const timeout = new Promise((_, reject) =>
setTimeout(() => reject(new Error('Timeout')), ms)
);
return Promise.race([fetch(url), timeout]);
}
// allSettled — independent operations
const results = await Promise.allSettled([
updateDatabase(record),
sendNotification(user),
updateCache(key),
]);
const failures = results.filter(r => r.status === 'rejected');
if (failures.length) console.error('Partial failures:', failures);
The race timeout above has two production flaws: the timer keeps running after fetch wins (keeping a Node process alive for ms), and losing the race does not cancel the request — the network call continues. The modern version cancels for real:
async function fetchWithTimeoutAbort(url, ms) {
const res = await fetch(url, { signal: AbortSignal.timeout(ms) }); // rejects with TimeoutError
return res.json();
}
// Combine a user cancel and a timeout:
// fetch(url, { signal: AbortSignal.any([controller.signal, AbortSignal.timeout(5000)]) })
Common wrong answer: "Promise.all cancels the other promises when one rejects." Promises are not cancellable; the others keep running and their results are discarded.
Follow-up: What do all and any return for an empty array? Promise.all([]) fulfils with [] immediately; Promise.any([]) rejects with an AggregateError; Promise.race([]) stays pending forever.
Q: Common async/await gotchas
// GOTCHA 1: Sequential when you meant parallel
// BAD — each await blocks the next
const user = await fetchUser(id);
const posts = await fetchPosts(id);
const comments = await fetchComments(id);
// GOOD — run in parallel
const [user, posts, comments] = await Promise.all([
fetchUser(id),
fetchPosts(id),
fetchComments(id),
]);
// GOTCHA 2: Forgetting error handling
// BAD — unhandled rejection
async function process() {
const data = await riskyOperation(); // no try/catch
}
// GOOD
async function process() {
try {
const data = await riskyOperation();
} catch (err) {
logger.error('Operation failed', { error: err.message });
throw err; // re-throw if caller should handle it
}
}
// GOTCHA 3: forEach does not await
const ids = [1, 2, 3];
// BAD — fires all at once, does not wait
ids.forEach(async (id) => {
await processItem(id);
});
// GOOD — sequential
for (const id of ids) {
await processItem(id);
}
// GOOD — parallel
await Promise.all(ids.map(id => processItem(id)));
Unhandled Promise Rejections Crash Node.js
Since Node.js 15, unhandled promise rejections terminate the process by default. Always handle rejections or use a global handler: process.on('unhandledRejection', handler).
A note on Gotcha 2: the "BAD" version is only an unhandled rejection if the caller also ignores the returned promise; an async function converts a throw into a rejected promise. The real bug is fire-and-forget calls (process(); without await or .catch). Gotcha 4, the subtle one: "parallel" Promise.all over 10,000 ids opens 10,000 requests at once — use a concurrency limit (Part 4).
Common wrong answer: "try/catch around promise.then(...) catches its errors." A synchronous try exits long before the rejection; only await inside try brings the rejection back into the catch.
Follow-up: With Promise.all, if two promises reject, what happens to the second rejection? It is handled internally by all (no unhandled-rejection warning) but ignored. Use allSettled if you need every error.
Q: then(onOk, onErr) vs then(onOk).catch(onErr) — and how does finally pass values?
then(onOk, onErr) only catches rejections of the previous promise; an error thrown inside onOk goes past onErr. .then(onOk).catch(onErr) also catches errors thrown by onOk. finally callbacks receive no argument, and their return value is ignored (unless they throw or return a rejected promise) — the original value flows through.
Promise.reject(new Error('boom'))
.then(() => console.log('then'))
.catch((e) => console.log('caught', e.message)) // caught boom
.finally(() => console.log('finally')) // finally
.then((v) => console.log('after', v)); // after undefined (catch returned undefined)
Promise.resolve(1).then(2).then(console.log); // 1 — non-function handlers are ignored
Promise.resolve(1).finally(() => 99).then(console.log); // 1 — finally's return is ignored
Printed order (verified): caught boom, 1, finally, 1, after undefined — the three chains interleave by microtask hops.
Common wrong answer: "after prints boom" — once catch handles the error, the chain is fulfilled with catch's return value.
Follow-up: When would you deliberately use the two-argument form? When you want to handle a failure of one step without also swallowing bugs in the success handler — e.g. fetchConfig().then(useConfig, useDefaults).
Generators and Iterators
Q: What are generators and when are they useful?
Generators are functions that can be paused and resumed. They produce an iterator that yields values on demand — useful for lazy evaluation, infinite sequences, and custom iteration.
function* fibonacci() {
let a = 0, b = 1;
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
// Take first 10 Fibonacci numbers
function take(iterator, n) {
const result = [];
for (const value of iterator) {
result.push(value);
if (result.length >= n) break;
}
return result;
}
console.log(take(fibonacci(), 10));
// [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
// Pagination generator
async function* fetchPages(baseUrl) {
let page = 1;
while (true) {
const response = await fetch(`${baseUrl}?page=${page}`);
const data = await response.json();
if (data.items.length === 0) return;
yield data.items;
page++;
}
}
for await (const items of fetchPages('/api/users')) {
renderItems(items);
}
Generators are two-way: next(value) sends a value into the generator as the result of the paused yield. The first next() argument is discarded because there is no paused yield to receive it.
function* conversation() {
const a = yield 'first';
console.log('got', a);
const b = yield a * 2;
return a + b;
}
const it = conversation();
console.log(it.next('ignored')); // { value: 'first', done: false }
console.log(it.next(5)); // logs 'got 5', then { value: 10, done: false }
console.log(it.next(1)); // { value: 6, done: true }
console.log(it.next()); // { value: undefined, done: true }
Common wrong answer: "for...of returns the generator's return value." It ignores the done: true value — the 6 above would never appear in a for...of.
Follow-up: How did generators power async code before async/await? Libraries like co yielded promises and called next(resolvedValue) when they settled — async/await is essentially that pattern built into the language.
Q: What is the iterator protocol? Make a class iterable.
An iterable has a [Symbol.iterator]() method that returns an iterator: an object with next() returning { value, done }. Spread, for...of, destructuring, Array.from, new Map(iterable), Promise.all and yield* all consume this protocol. An iterator may also implement return(), which for...of calls on early exit (break, throw, return) so the source can clean up.
class Range {
constructor(start, end) { this.start = start; this.end = end; }
*[Symbol.iterator]() {
for (let i = this.start; i < this.end; i++) yield i;
}
}
console.log([...new Range(1, 4)], Math.max(...new Range(0, 10))); // [1, 2, 3] 9
// Hand-written iterator, no generator
const countdown = {
[Symbol.iterator]() {
let n = 3;
return {
next: () => (n > 0 ? { value: n--, done: false } : { value: undefined, done: true }),
return: () => { console.log('cleanup'); return { done: true }; },
};
},
};
for (const n of countdown) { console.log(n); if (n === 2) break; } // 3, 2, cleanup
Common wrong answer: "Iterables and iterators are the same." A Range can be iterated many times because each [Symbol.iterator]() call returns a fresh iterator; a generator object is a one-shot iterator that is also iterable (it returns itself).
Follow-up: Why is a plain object not iterable? Because objects have no defined order semantics for a "sequence"; use Object.entries(obj).
Modules
Q: ESM vs CommonJS — what are the real differences?
CommonJS (require) | ES Modules (import) | |
|---|---|---|
| Loading | Synchronous, at runtime | Asynchronous; graph parsed and linked before execution |
| Exports | A plain object (module.exports) — values copied on destructure | Live bindings — importers see updates |
| Static analysis | Hard (require can be computed) | Imports are static → tree-shaking works |
Top-level await | No | Yes |
this at top level | module.exports | undefined |
| Strict mode | Opt-in | Always |
| File-level vars | __dirname, __filename, require | import.meta.url, import.meta.dirname/filename (Node 20.11+) |
| Browser support | No (needs a bundler) | Native |
In Node, a file is ESM if it ends in .mjs, or .js with "type": "module" in the nearest package.json. ESM can import CommonJS (you get module.exports as the default export, plus statically detectable named exports). Since Node 22.12 and 20.19, CommonJS can require() a synchronous ES module (one without top-level await) without a flag — verified below on 22.13.
// counter.mjs
export let count = 0;
export function inc() { count++; }
// main.mjs
import { count, inc } from './counter.mjs';
console.log(count); // 0
inc();
console.log(count); // 1 — live binding
// count = 5; // TypeError: imports are read-only views
// c.cjs: let count = 0; module.exports = { count, inc() { count++; } };
// m.cjs: const { count, inc } = require('./c.cjs'); inc(); console.log(count); // 0 — a copy
// m.cjs: const esm = require('./counter.mjs'); // works on Node 22.12+ — a Module namespace object
Common wrong answer: "ESM is just new syntax for require." The loading model (link-then-evaluate), live bindings, and async evaluation are fundamentally different.
Follow-up: What's the dual-package hazard? Publishing both CJS and ESM builds means an app can load two copies of your package (one via require, one via import), with separate state and failing instanceof checks. Mitigate with a single format plus a thin wrapper, or rely on require(esm) and ship ESM only.
Q: Dynamic import(), top-level await, and import attributes
import() is a function-like expression that returns a promise of the module namespace; it works in both ESM and CJS and is how bundlers create split points. Top-level await (ES2022) lets a module await during evaluation; modules that import it wait for it, which can delay app start — use it for configuration and feature detection, not for slow network calls on the critical path. Import attributes (ES2025) declare the type of non-JS modules: import data from './data.json' with { type: 'json' }.
// main.mjs
const { default: os } = await import('node:os'); // top-level await + dynamic import
console.log(typeof os.cpus); // 'function'
const pkg = await import('./package.json', { with: { type: 'json' } }).catch(() => null);
console.log(pkg ? 'loaded json module' : 'no package.json here');
const locale = 'en';
const messages = { en: () => ({ hi: 'Hello' }) }[locale](); // in a bundler: await import(`./i18n/${locale}.js`)
console.log(messages.hi);
Common wrong answer: "import() makes code lazy for free." Bundlers can only split on static string paths or analyzable templates; a fully computed path forces them to include everything or fail.
Follow-up: Why do JSON imports need with { type: 'json' }? Security: without it, a server could respond to data.json with JavaScript and the browser would execute it. The attribute makes the loader reject non-JSON MIME types.
Part 3: Staff
Memory and Garbage Collection
Q: How does garbage collection work in JavaScript engines, and what counts as a leak?
Engines use reachability: starting from roots (the stack, globals, active closures, handles held by the host), anything that can be reached is live; everything else is garbage. V8's collector is generational — most objects die young, so a cheap scavenger copies survivors out of a small young generation, and a concurrent, incremental mark-sweep-compact collector handles the old generation. Reference counting is not used, so cycles are collected fine.
A "leak" in a GC'd language is memory that is still reachable but no longer needed. Typical culprits: unbounded caches and maps, listeners never removed, timers (setInterval) that capture big objects, detached DOM nodes still referenced from JS, and closures that keep a large scope alive.
// Node: watch a leak grow, then fix it
const cache = new Map();
function handle(id) {
cache.set(id, Buffer.alloc(1024 * 10)); // never evicted: leak
}
for (let i = 0; i < 5000; i++) handle(i);
console.log(`${(process.memoryUsage().arrayBuffers / 1e6).toFixed(0)} MB held`); // roughly 51 MB
cache.clear(); // the fix: bound or evict (see LRU in Part 4)
To find one: take two or three heap snapshots (Chrome DevTools Memory tab, or node --inspect / v8.writeHeapSnapshot()), perform the suspect action in between, and use the Comparison view sorted by "# Delta"; then follow the retainers path of a leaked object back to the root that holds it.
Common wrong answer: "Set it to null and call gc()." Nulling one reference doesn't help if another path retains the object, and forcing GC changes nothing about reachability.
Follow-up: Why do detached DOM nodes leak so much? One retained node keeps its whole subtree (and listeners and their closures) alive. DevTools' snapshot filter "Detached" lists them.
Q: When would you use WeakMap?
WeakMap holds weak references to its keys. If no other reference to the key exists, the entry is garbage collected. This is ideal for associating metadata with objects without preventing their cleanup.
// Private data pattern
const privateData = new WeakMap();
class User {
constructor(name, password) {
this.name = name;
privateData.set(this, { password }); // private, GC-friendly
}
checkPassword(attempt) {
return privateData.get(this).password === attempt;
}
}
// DOM metadata without memory leaks
const elementTimers = new WeakMap();
function trackHover(element) {
element.addEventListener('mouseenter', () => {
elementTimers.set(element, Date.now());
});
element.addEventListener('mouseleave', () => {
const entered = elementTimers.get(element);
console.log(`Hovered for ${Date.now() - entered}ms`);
});
// When element is removed from DOM and dereferenced,
// the WeakMap entry is automatically garbage collected
}
Because entries can vanish at any time, WeakMap is not iterable and has no size — the result would depend on GC timing. Keys must be objects (or, since ES2023, non-registered symbols). Values are held strongly while the key is alive — the structure is technically an ephemeron table: a value referencing its own key does not keep the entry alive.
Common wrong answer: "WeakMap values are weak." Only the keys are; a big value stays as long as its key is reachable.
Follow-up: Implement a per-object memoize that can't leak. const cache = new WeakMap(); function area(shape) { if (!cache.has(shape)) cache.set(shape, expensive(shape)); return cache.get(shape); } — when shape is dropped, so is its cached result.
Q: What are WeakRef and FinalizationRegistry, and why does the spec warn against them?
WeakRef (ES2021) holds an object without keeping it alive; deref() returns the object or undefined once collected. FinalizationRegistry lets you register a callback that may run some time after an object is collected. Both expose GC timing, which is non-deterministic and differs across engines, so the spec's own guidance is to avoid them unless you have a measured need — typically caches of expensive-to-recreate resources, or cleaning up native/wasm memory as a safety net.
// node --expose-gc weakref.mjs
let big = { data: new Array(1e6).fill(0) };
const ref = new WeakRef(big);
const registry = new FinalizationRegistry((label) => console.log('collected', label));
registry.register(big, 'big object');
console.log(ref.deref() !== undefined); // true
big = null;
setTimeout(() => {
globalThis.gc?.();
setTimeout(() => console.log('deref after gc:', ref.deref()), 0); // usually undefined
}, 0);
// 'collected big object' may print — or not — before the process exits
Two subtleties: within a single synchronous job a deref()ed object stays alive (the engine keeps targets alive until the end of the current job), and finalizers are not guaranteed to run at all, e.g. on process exit.
Common wrong answer: "Use FinalizationRegistry to close files or DB connections." Cleanup that must happen needs explicit close() — or using declarations with Symbol.dispose (the explicit resource management proposal, shipping in recent V8-based runtimes — check your targets) — never a GC callback.
Follow-up: Build a cache that keeps values only while something else uses them. Map<key, WeakRef<value>> plus a FinalizationRegistry that deletes the map entry when the value is collected (check that the entry still points at a dead ref before deleting — the key may have been re-set).
Proxy and Reflect
Q: How does Proxy work?
Proxy wraps an object and intercepts fundamental operations (get, set, delete, etc.). Combined with Reflect, it enables metaprogramming patterns like validation, logging, and reactive systems.
// Validation proxy
function createValidated(target, validators) {
return new Proxy(target, {
set(obj, prop, value) {
if (validators[prop] && !validators[prop](value)) {
throw new TypeError(`Invalid value for ${prop}: ${value}`);
}
return Reflect.set(obj, prop, value);
},
});
}
const user = createValidated({}, {
age: (v) => typeof v === 'number' && v >= 0 && v <= 150,
email: (v) => typeof v === 'string' && v.includes('@'),
});
user.age = 25; // OK
user.email = 'a@b.com'; // OK
user.age = -5; // TypeError: Invalid value for age: -5
There are 13 traps, one per internal method: get, set, has, deleteProperty, ownKeys, getOwnPropertyDescriptor, defineProperty, getPrototypeOf, setPrototypeOf, isExtensible, preventExtensions, apply and construct. Traps must respect invariants — for example, get can't report a different value for a non-configurable, non-writable property, and ownKeys must list every non-configurable own key — or the engine throws a TypeError.
Common wrong answer: "A proxy copies the object." It forwards to the live target; changes through the proxy hit the target, and the target can still be mutated directly (bypassing the traps).
Follow-up: What is a revocable proxy? Proxy.revocable(target, handler) returns { proxy, revoke }; after revoke(), every operation throws — used to hand out capabilities that can be withdrawn.
Q: Why use Reflect and the receiver argument? Build a small reactive store.
Each Reflect method has the same signature as the matching trap and performs the default behaviour, returning a boolean instead of throwing. Passing receiver matters with getters and inheritance: Reflect.get(target, key, receiver) runs a getter with this === receiver (the proxy), so dependencies accessed inside the getter are also tracked. target[key] would run it with this === target and bypass the proxy.
function reactive(target, onChange) {
return new Proxy(target, {
get(t, key, receiver) {
const v = Reflect.get(t, key, receiver);
return v && typeof v === 'object' ? reactive(v, onChange) : v; // lazy deep wrapping
},
set(t, key, value, receiver) {
const old = t[key];
const ok = Reflect.set(t, key, value, receiver);
if (ok && old !== value) onChange(key, old, value);
return ok; // returning false throws in strict mode
},
});
}
const state = reactive({ user: { name: 'A' }, n: 1 },
(k, o, v) => console.log(`${String(k)}: ${o} -> ${v}`));
state.n = 2; // n: 1 -> 2
state.user.name = 'B'; // name: A -> B
state.n = 2; // no output — unchanged
This is the core idea behind Vue 3's reactivity and MobX. A production version caches wrappers in a WeakMap (so state.user === state.user), tracks reads to know which effects depend on which keys, and batches notifications.
Common wrong answer: "Forgetting to return true from set is harmless." In strict-mode code, a falsy return from the set trap throws a TypeError.
Follow-up: What's the performance cost? Proxied property access is far slower than a plain property access because it defeats inline caches; keep proxies out of hot inner loops and unwrap (toRaw) for heavy computation.
Modern JavaScript (ES2023–ES2025)
Feature availability below was checked on Node 22.13 and Node 24. ES2024 features are in all current evergreen browsers; check Baseline or MDN for older targets.
| Feature | Edition | Node | Notes |
|---|---|---|---|
toSorted/toReversed/with/findLast | ES2023 | 20+ | Non-mutating arrays |
Object.groupBy, Map.groupBy | ES2024 | 21+ | Null-prototype result |
Promise.withResolvers | ES2024 | 22+ | Deferred pattern |
Array.fromAsync | ES2024 | 22+ | Collects async iterables |
Set methods (union, intersection, ...) | ES2025 | 22+ | |
Iterator helpers (map, filter, take, ...) | ES2025 | 22+ | Lazy |
Promise.try, RegExp.escape, Float16Array | ES2025 | 24+ (not in 22.13) | |
| Import attributes / JSON modules | ES2025 | 22+ | with { type: 'json' } |
Q: What do Object.groupBy and Map.groupBy do, and what's the catch?
They bucket an iterable by a key returned from a callback — replacing the classic reduce boilerplate. Object.groupBy returns an object with a null prototype (so a group named "constructor" or "__proto__" is safe, but result.hasOwnProperty doesn't exist); keys are coerced to strings. Map.groupBy keeps keys as-is, so you can group by objects or booleans.
const inventory = [
{ name: 'apple', type: 'fruit', qty: 5 },
{ name: 'leek', type: 'veg', qty: 0 },
{ name: 'pear', type: 'fruit', qty: 2 },
];
const byType = Object.groupBy(inventory, ({ type }) => type);
console.log(Object.keys(byType), Object.getPrototypeOf(byType)); // ['fruit', 'veg'] null
const stock = Map.groupBy(inventory, (i) => i.qty > 0);
console.log(stock.get(false).map((i) => i.name)); // ['leek']
Common wrong answer: "It's Array.prototype.groupBy." The prototype method was renamed to a static because adding groupBy to arrays broke existing websites (a library had patched it) — the same "don't break the web" story as flatten becoming flat.
Follow-up: How do you count per group? Object.fromEntries(Object.entries(byType).map(([k, v]) => [k, v.length])).
Q: What is Promise.withResolvers for?
It returns { promise, resolve, reject } — the "deferred" pattern without the let resolve; new Promise(r => resolve = r) dance. Use it when the code that settles the promise is not where the promise is created: event-to-promise adapters, request/response matching over a WebSocket, test harnesses.
function nextMessage(emitter) {
const { promise, resolve, reject } = Promise.withResolvers();
emitter.addEventListener('message', (e) => resolve(e.data), { once: true });
emitter.addEventListener('error', reject, { once: true });
return promise;
}
const target = new EventTarget();
nextMessage(target).then((d) => console.log('got', d)); // got hello
const ev = new Event('message'); ev.data = 'hello';
target.dispatchEvent(ev);
Common wrong answer: "It's for creating already-resolved promises." That is Promise.resolve(v).
Follow-up: What's the risk? A deferred that is never settled leaks its callbacks forever — pair it with a timeout or AbortSignal.
Q: What are the new Set methods?
ES2025 added set algebra on Set.prototype: union, intersection, difference, symmetricDifference (return new Sets) and isSubsetOf, isSupersetOf, isDisjointFrom (return booleans). The argument only needs to be set-like — an object with size, has and keys — so a Map works too.
const a = new Set([1, 2, 3, 4]);
const b = new Set([3, 4, 5]);
console.log(a.union(b)); // Set(5) {1, 2, 3, 4, 5}
console.log(a.intersection(b)); // Set(2) {3, 4}
console.log(a.difference(b)); // Set(2) {1, 2}
console.log(a.symmetricDifference(b)); // Set(3) {1, 2, 5}
console.log(a.isSubsetOf(new Set([1, 2, 3, 4, 5])), a.isDisjointFrom(new Set([9]))); // true true
const roles = new Map([['admin', true]]);
console.log(new Set(['admin', 'dev']).intersection(roles)); // Set(1) {'admin'}
Common wrong answer: "a.union([5, 6]) works." An array is not set-like (no size/has) — it throws a TypeError; wrap it: a.union(new Set([5, 6])).
Follow-up: What's the complexity of intersection? The spec iterates the smaller of the two and calls has on the other, so roughly O(min(|a|, |b|)).
Q: What are iterator helpers, and why do they matter?
ES2025 added map, filter, take, drop, flatMap, reduce, toArray, forEach, some, every and find to Iterator.prototype, plus Iterator.from() to wrap any iterator. Unlike array methods they are lazy: nothing runs until you pull values, and infinite sequences are fine.
function* naturals() { let i = 0; while (true) yield i++; }
const firstOddSquares = naturals()
.filter((n) => n % 2)
.map((n) => n * n)
.take(4)
.toArray();
console.log(firstOddSquares); // [1, 9, 25, 49]
const m = new Map([['a', 1], ['b', 2]]);
console.log(m.values().map((v) => v * 10).toArray()); // [10, 20] — no intermediate array from Map
Common wrong answer: "naturals().map(...) returns an array." It returns another iterator — call .toArray() or spread it. And helpers don't exist on async iterators yet (async iterator helpers are a separate proposal).
Follow-up: When is laziness a trap? Iterators are one-shot: consuming m.values().map(f) twice gives an empty second result. If you need to re-read, materialize with toArray().
Q: What else landed in ES2025, and how do you decide whether you can use a new feature?
ES2025 also includes Promise.try(fn) (runs fn and always returns a promise, turning synchronous throws into rejections), RegExp.escape(str) (safe interpolation of user text into a regex), Float16Array with Math.f16round, regex pattern modifiers ((?i:...)) and duplicate named capture groups in alternatives. These were verified on Node 24; Node 22.13 lacks Promise.try, RegExp.escape and Float16Array.
// Run on Node 24+
console.log(RegExp.escape('a.b*c')); // \x61\.b\*c — leading letter is hex-escaped too
const userInput = 'file(1).txt';
console.log(new RegExp(`^${RegExp.escape(userInput)}$`).test('file(1).txt')); // true
console.log(await Promise.try(() => 42)); // 42
await Promise.try(() => { throw new Error('sync'); }).catch((e) => console.log(e.message)); // sync
Deciding whether to ship: a proposal is in the spec at TC39 stage 4, but what matters is your runtime matrix. For browsers, check Baseline status or your browserslist targets and let Babel/SWC transpile syntax and core-js polyfill APIs. For Node, check the minimum supported Node version in engines. Some features (WeakRef, Proxy, private fields' brand checks) can't be polyfilled faithfully.
Common wrong answer: "It's in the spec, so it's safe." Specs ship yearly; runtimes ship when they ship, and enterprise users lag years behind.
Follow-up: Why does RegExp.escape('abc') escape the first a? So the output is safe even when concatenated after \0-style escapes or \c — a leading alphanumeric is hex-escaped to avoid accidentally forming an escape sequence.
Part 4: Write It From Scratch
Interviewers grade these on edge cases, not on the happy path. Each implementation below was run against node:assert tests on Node 22. Level tags show where each is usually asked.
Q: Implement debounce
Level: junior–senior. Debounce delays execution until a pause in calls. Used for search input, window resize.
function debounce(fn, delay) {
let timerId;
return function (...args) {
clearTimeout(timerId);
timerId = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
}
// Usage
const searchInput = document.getElementById('search');
searchInput.addEventListener('input', debounce((e) => {
fetchResults(e.target.value);
}, 300));
The senior version adds a leading option, cancel() (call it on component unmount) and flush() (run the pending call now, e.g. before navigating away):
function debounceFull(fn, wait, { leading = false } = {}) {
let timer = null, lastArgs, lastThis;
const invoke = () => {
const args = lastArgs, ctx = lastThis;
lastArgs = lastThis = undefined;
return fn.apply(ctx, args);
};
function debounced(...args) {
lastArgs = args; lastThis = this;
const callNow = leading && timer === null;
clearTimeout(timer);
timer = setTimeout(() => { timer = null; if (lastArgs) invoke(); }, wait);
if (callNow) invoke(); // leading call consumes lastArgs, so no duplicate trailing call
}
debounced.cancel = () => { clearTimeout(timer); timer = null; lastArgs = lastThis = undefined; };
debounced.flush = () => { if (timer !== null) { clearTimeout(timer); timer = null; if (lastArgs) invoke(); } };
return debounced;
}
const calls = [];
const d = debounceFull((v) => calls.push(v), 20, { leading: true });
d(1); d(2); d(3);
setTimeout(() => console.log(calls), 50); // [1, 3]
Common wrong answer: Using an arrow function for the returned wrapper (loses the caller's this), or a leading-edge version that fires twice for a single call.
Follow-up: Debounce vs throttle for a search box? Debounce — you want the final query. For scroll position tracking, throttle — you want regular samples.
Q: Implement throttle
Level: junior–senior. Throttle ensures a function runs at most once per interval. Used for scroll handlers, rate limiting.
function throttle(fn, limit) {
let inThrottle = false;
return function (...args) {
if (!inThrottle) {
fn.apply(this, args);
inThrottle = true;
setTimeout(() => { inThrottle = false; }, limit);
}
};
}
// Trailing edge variant (fires on last call too)
function throttleWithTrailing(fn, limit) {
let lastArgs = null;
let timerId = null;
return function (...args) {
if (!timerId) {
fn.apply(this, args);
timerId = setTimeout(() => {
timerId = null;
if (lastArgs) {
fn.apply(this, lastArgs);
lastArgs = null;
}
}, limit);
} else {
lastArgs = args;
}
};
}
A subtlety in throttleWithTrailing: the trailing call is not itself followed by a cooldown window, so a call arriving right after it runs immediately — two calls can land closer than limit. A strict version restarts the timer after the trailing call.
Common wrong answer: Implementing throttle as debounce with a max wait, or dropping the final call (the user's last scroll position never gets processed).
Follow-up: For animation, what beats throttle(fn, 16)? requestAnimationFrame — schedule at most one rAF per frame and process the latest event inside it.
Q: Implement memoize
Level: junior–senior.
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;
};
}
// With max size (LRU-like)
function memoizeWithLimit(fn, maxSize = 100) {
const cache = new Map();
return function (...args) {
const key = JSON.stringify(args);
if (cache.has(key)) {
const value = cache.get(key);
cache.delete(key);
cache.set(key, value); // Move to end (most recent)
return value;
}
const result = fn.apply(this, args);
cache.set(key, result);
if (cache.size > maxSize) {
const oldestKey = cache.keys().next().value;
cache.delete(oldestKey);
}
return result;
};
}
Common wrong answer: Trusting JSON.stringify keys blindly: object arguments with different key order produce different keys, undefined and NaN collapse to null, functions and symbols vanish, and objects are compared by content instead of identity. For a single object argument, key a WeakMap by the object. For async functions, cache the promise and evict it on rejection.
Follow-up: Why does memoize not help a naive recursive fib? Because recursive calls go to the inner unmemoized fib unless the function calls the memoized wrapper by name: const fib = memoize((n) => n < 2 ? n : fib(n - 1) + fib(n - 2)).
Q: Implement Promise.all
Level: senior. Requirements: accept any iterable (not only arrays); keep result order by input index, not completion order; treat non-promises as values; reject on the first rejection; resolve [] for an empty input.
function promiseAll(iterable) {
return new Promise((resolve, reject) => {
const results = [];
let pending = 0;
let index = 0;
for (const item of iterable) {
const i = index++;
pending++;
Promise.resolve(item).then((value) => {
results[i] = value;
if (--pending === 0) resolve(results);
}, reject);
}
if (pending === 0) resolve(results); // empty iterable
});
}
const delay = (ms, v) => new Promise((r) => setTimeout(r, ms, v));
promiseAll([delay(20, 'a'), 'b', delay(5, 'c')]).then(console.log); // ['a', 'b', 'c']
promiseAll([]).then(console.log); // []
Common wrong answer: Checking results.length === input.length to detect completion. Assigning results[2] first makes length 3 immediately. Use a counter.
Follow-up: Why Promise.resolve(item) instead of item.then? It handles plain values and foreign thenables uniformly.
Q: Implement Promise.allSettled, Promise.race and Promise.any
Level: senior.
function promiseAllSettled(iterable) {
return promiseAll(Array.from(iterable, (p) =>
Promise.resolve(p).then(
(value) => ({ status: 'fulfilled', value }),
(reason) => ({ status: 'rejected', reason }),
)));
}
function promiseRace(iterable) {
return new Promise((resolve, reject) => {
for (const item of iterable) Promise.resolve(item).then(resolve, reject); // first settle wins
});
}
function promiseAny(iterable) {
return new Promise((resolve, reject) => {
const errors = [];
let pending = 0, index = 0;
for (const item of iterable) {
const i = index++;
pending++;
Promise.resolve(item).then(resolve, (err) => {
errors[i] = err;
if (--pending === 0) reject(new AggregateError(errors, 'All promises were rejected'));
});
}
if (pending === 0) reject(new AggregateError([], 'All promises were rejected'));
});
}
promiseAllSettled([1, Promise.reject(2)]).then(console.log);
// [{ status: 'fulfilled', value: 1 }, { status: 'rejected', reason: 2 }]
Common wrong answer: In race, adding "if already settled, return" guards. They're unnecessary — a promise ignores every resolve/reject after the first.
Follow-up: Write promiseTimeout(p, ms) that rejects and clears its timer. Race p against a timer promise, then clearTimeout in a finally.
Q: Run async tasks with a concurrency limit
Level: senior–staff. Promise.all(items.map(fn)) starts everything at once. The worker-pool pattern starts limit workers that each pull the next index:
async function mapWithConcurrency(items, limit, fn) {
const results = new Array(items.length);
let next = 0;
async function worker() {
while (next < items.length) {
const i = next++; // safe: single-threaded, no await between read and increment
results[i] = await fn(items[i], i);
}
}
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
return results;
}
let active = 0, peak = 0;
mapWithConcurrency([1, 2, 3, 4, 5, 6], 2, async (x) => {
active++; peak = Math.max(peak, active);
await new Promise((r) => setTimeout(r, 5));
active--;
return x * 2;
}).then((out) => console.log(out, 'peak', peak)); // [2, 4, 6, 8, 10, 12] peak 2
Common wrong answer: Chunking into batches of limit and await Promise.all per batch — one slow item stalls the whole batch.
Follow-up: What happens on the first rejection? Promise.all rejects, but other workers keep pulling items. Add a shared failed flag or AbortSignal so workers stop.
Q: Implement deep clone
Level: senior.
function deepClone(obj, seen = new WeakMap()) {
// Primitives and null
if (obj === null || typeof obj !== 'object') return obj;
// Handle circular references
if (seen.has(obj)) return seen.get(obj);
// Handle Date
if (obj instanceof Date) return new Date(obj.getTime());
// Handle RegExp
if (obj instanceof RegExp) return new RegExp(obj.source, obj.flags);
// Handle Map
if (obj instanceof Map) {
const map = new Map();
seen.set(obj, map);
obj.forEach((value, key) => map.set(deepClone(key, seen), deepClone(value, seen)));
return map;
}
// Handle Set
if (obj instanceof Set) {
const set = new Set();
seen.set(obj, set);
obj.forEach(value => set.add(deepClone(value, seen)));
return set;
}
// Handle Array and Object
const clone = Array.isArray(obj) ? [] : {};
seen.set(obj, clone);
for (const key of Reflect.ownKeys(obj)) {
clone[key] = deepClone(obj[key], seen);
}
return clone;
}
Known limits worth saying out loud: class instances come back as plain objects (fix with Object.create(Object.getPrototypeOf(obj))); Reflect.ownKeys copies non-enumerable properties as enumerable ones and invokes getters; typed arrays, ArrayBuffers and Errors aren't special-cased; and very deep structures overflow the stack (use an explicit stack). Functions are returned by reference — usually correct.
const a = { n: 1, when: new Date(0), tags: new Set(['x']) };
a.self = a;
const b = deepClone(a);
console.log(b.self === b, b.when !== a.when, b.tags.has('x')); // true true true
Common wrong answer: Forgetting cycles (stack overflow) or checking typeof obj === 'object' without excluding null.
Follow-up: When would you use structuredClone instead? Almost always in production — it's native, faster, and handles more types; write your own only to preserve prototypes or custom types.
Q: Implement Function.prototype.bind
Level: senior. The parts candidates miss: partial application of arguments, and behaving correctly under new (the bound this is ignored and the result must be an instance of the original function).
Function.prototype.myBind = function (thisArg, ...preset) {
const target = this;
if (typeof target !== 'function') throw new TypeError('myBind called on non-function');
function bound(...args) {
if (new.target) {
// Called with `new`: ignore thisArg, construct the original
return Reflect.construct(target, [...preset, ...args], new.target);
}
return target.apply(thisArg, [...preset, ...args]);
}
if (target.prototype) bound.prototype = Object.create(target.prototype);
return bound;
};
function greet(greeting, punct) { return `${greeting}, ${this.name}${punct}`; }
console.log(greet.myBind({ name: 'Ada' }, 'Hi')('!')); // Hi, Ada!
function Point(x, y) { this.x = x; this.y = y; }
const AtX1 = Point.myBind(null, 1);
const pt = new AtX1(2);
console.log(pt.x, pt.y, pt instanceof Point); // 1 2 true
Common wrong answer: return () => fn.apply(ctx, arguments) — arguments in an arrow refers to the outer function's arguments, and there's no new support.
Follow-up: Implement call without call/apply. Temporarily attach the function to the object under a unique Symbol key, invoke it as a method, then delete the key.
Q: Implement curry
Level: junior–senior.
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn.apply(this, args);
}
return function (...moreArgs) {
return curried.apply(this, [...args, ...moreArgs]);
};
};
}
// Usage
const add = (a, b, c) => a + b + c;
const curriedAdd = curry(add);
curriedAdd(1)(2)(3); // 6
curriedAdd(1, 2)(3); // 6
curriedAdd(1)(2, 3); // 6
curriedAdd(1, 2, 3); // 6
Common wrong answer: Relying on fn.length without knowing its rules: it counts parameters before the first default or rest parameter. ((a, b = 2, c) => {}).length is 1, so curry would call it after one argument. Accept an explicit arity: function curry(fn, arity = fn.length).
Follow-up: Support infinite currying: sum(1)(2)(3)() → 6. Return a function that accumulates until it's called with no arguments.
Q: Implement an EventEmitter
Level: senior. Requirements: on, off, once, emit; on returns an unsubscribe function; removing a listener during emit must not skip the next one; off must work for a function registered with once; emitting 'error' with no listener throws (matching Node).
class EventEmitter {
#listeners = new Map();
on(event, fn) {
if (!this.#listeners.has(event)) this.#listeners.set(event, []);
this.#listeners.get(event).push(fn);
return () => this.off(event, fn);
}
once(event, fn) {
const wrapper = (...args) => { this.off(event, wrapper); fn.apply(this, args); };
wrapper.original = fn; // so off(event, fn) can find it
return this.on(event, wrapper);
}
off(event, fn) {
const list = this.#listeners.get(event);
if (!list) return;
const i = list.findIndex((l) => l === fn || l.original === fn);
if (i !== -1) list.splice(i, 1);
if (list.length === 0) this.#listeners.delete(event);
}
emit(event, ...args) {
const list = this.#listeners.get(event);
if (!list) {
if (event === 'error') throw args[0];
return false;
}
for (const fn of [...list]) fn.apply(this, args); // iterate a snapshot
return true;
}
}
const ee = new EventEmitter();
const log = [];
const unsubscribe = ee.on('x', (v) => log.push('on:' + v));
ee.once('x', (v) => log.push('once:' + v));
ee.emit('x', 1); ee.emit('x', 2); unsubscribe();
console.log(log, ee.emit('x', 3)); // ['on:1', 'once:1', 'on:2'] false
Common wrong answer: Iterating the live array while once wrappers splice themselves out — the listener after a once gets skipped.
Follow-up: Should one listener's throw stop the others? Node's emitter lets it propagate and stop the loop. A UI event bus usually catches per listener and reports, so one buggy subscriber can't break the rest.
Q: Implement an LRU cache with O(1) operations
Level: senior. A Map iterates in insertion order, so "delete and re-insert" moves a key to the most-recent end, and keys().next() is the least-recent key. Both are O(1).
class LRUCache {
#map = new Map();
constructor(capacity) { this.capacity = capacity; }
get(key) {
if (!this.#map.has(key)) return undefined;
const value = this.#map.get(key);
this.#map.delete(key);
this.#map.set(key, value); // now most recently used
return value;
}
set(key, value) {
if (this.#map.has(key)) this.#map.delete(key);
this.#map.set(key, value);
if (this.#map.size > this.capacity) {
this.#map.delete(this.#map.keys().next().value); // evict least recently used
}
return this;
}
get size() { return this.#map.size; }
}
const lru = new LRUCache(2);
lru.set('a', 1).set('b', 2);
lru.get('a'); // 'a' is now most recent
lru.set('c', 3); // evicts 'b'
console.log(lru.get('b'), lru.get('a'), lru.get('c')); // undefined 1 3
Common wrong answer: Using an array plus indexOf for recency — O(n) per access. Also, if (this.#map.get(key)) fails for falsy values like 0; use has.
Follow-up: Implement it without Map ordering, as in other languages. A hash map from key to node plus a doubly linked list with sentinel head/tail nodes — see Linked Lists and Hash Tables.
Q: Implement array flat
Level: junior.
// Recursive
function flat(arr, depth = 1) {
if (depth <= 0) return arr.slice();
return arr.reduce((acc, val) => {
if (Array.isArray(val)) {
acc.push(...flat(val, depth - 1));
} else {
acc.push(val);
}
return acc;
}, []);
}
// Iterative (infinite depth)
function flatIterative(arr) {
const stack = [...arr];
const result = [];
while (stack.length) {
const next = stack.pop();
if (Array.isArray(next)) {
stack.push(...next);
} else {
result.push(next);
}
}
return result.reverse();
}
console.log(flat([1, [2, [3, [4]]]], Infinity)); // [1, 2, 3, 4]
A related ask is flattening a nested object into dot-path keys (for form errors, config, analytics):
function flattenObject(obj, prefix = '', out = {}) {
for (const [k, v] of Object.entries(obj)) {
const key = prefix ? `${prefix}.${k}` : k;
if (v && typeof v === 'object' && !Array.isArray(v) && Object.keys(v).length) flattenObject(v, key, out);
else out[key] = v;
}
return out;
}
console.log(flattenObject({ a: 1, b: { c: 2, d: { e: 3 } }, f: [1] }));
// { a: 1, 'b.c': 2, 'b.d.e': 3, f: [1] }
Common wrong answer: acc.push(...hugeArray) for very large arrays — spreading hundreds of thousands of elements as arguments can throw RangeError: Maximum call stack size exceeded. Push in a loop for big inputs. Also, native flat skips holes ([1, , 2].flat() is [1, 2]). The recursive version matches because reduce skips holes too, but flatIterative turns them into undefined (spread fills holes) — verified: [1, undefined, 2].
Follow-up: Implement it as a generator — function* flatGen(a) { for (const x of a) Array.isArray(x) ? yield* flatGen(x) : yield x; } — lazy and memory-light.
Part 5: Output Prediction Puzzles
Cover the answer, predict, then check. Every output was verified on Node 22. Run the snippets as .mjs (strict mode) unless noted.
Puzzle: Coercion barrage
console.log([] == ![]);
console.log(Math.max(), Math.min());
console.log(typeof typeof 1);
console.log(1 < 2 < 3, 3 > 2 > 1);
Answer: true, -Infinity Infinity, 'string', true false. ![] is false (objects are truthy) and both sides become 0. Math.max() with no arguments returns the identity for max, -Infinity. typeof always returns a string. 3 > 2 > 1 is (true) > 1 → 1 > 1 → false.
Trap: Reasoning "an empty array is falsy". Follow-up: List the falsy values — false, 0, -0, 0n, '', null, undefined, NaN (and the legacy document.all).
Puzzle: this in an ES module
const obj = {
name: 'obj',
regular() { return this?.name; },
arrow: () => String(this),
nested() { return [1].map(function () { return String(this); })[0]; },
nestedArrow() { return [1].map(() => this.name)[0]; },
};
console.log(obj.regular());
console.log(obj.arrow());
console.log(obj.nested());
console.log(obj.nestedArrow());
const r = obj.regular;
console.log(r());
Answer: obj, undefined, undefined, obj, undefined. The arrow property is defined at module top level, where this is undefined in ESM (it would be module.exports, printing [object Object], in a CommonJS file). The inner function passed to map is a plain call in strict mode. Trap: expecting obj.arrow() to see obj because "it's called on obj". Follow-up: How would you make nested see obj without an arrow? Pass thisArg: [1].map(function () { return this.name; }, this).
Puzzle: Hoisting and shadowing
var x = 1;
function outer() {
console.log(x);
var x = 2;
function inner() { console.log(x); }
inner();
}
outer();
try { console.log(tdz); } catch (e) { console.log(e.name); }
let tdz = 1;
Answer: undefined, 2, ReferenceError. The local var x is hoisted to the top of outer, shadowing the global from the first line. Trap: answering 1 for the first log. Follow-up: Change var x = 2 to let x = 2 — what now? The first console.log(x) throws ReferenceError (TDZ), because the local let still shadows the global.
Puzzle: finally overrides return
function f() { try { return 'try'; } finally { console.log('finally runs'); } }
console.log(f());
function g() { try { return 'try'; } finally { return 'finally'; } }
console.log(g());
Answer: finally runs, try, then finally. finally always runs; a return (or throw) inside it replaces the pending completion. Trap: thinking return skips finally. Follow-up: Why do linters flag return in finally? It silently swallows exceptions from the try block (ESLint no-unsafe-finally).
Puzzle: Object key order
console.log(Object.keys({ b: 1, 2: 1, a: 1, 1: 1, [Symbol('s')]: 1 }));
Answer: ['1', '2', 'b', 'a']. Integer-like keys come first in ascending numeric order, then string keys in insertion order; symbols are excluded from Object.keys (use Reflect.ownKeys). Trap: "objects have no order" — the order has been specified since ES2015 for ownKeys and since ES2020 for for...in/Object.keys. Follow-up: Need guaranteed insertion order for numeric-looking IDs? Use a Map.
Puzzle: Microtasks inside a timer
setTimeout(() => {
console.log('T1');
Promise.resolve().then(() => console.log('P-in-T1'));
}, 0);
setTimeout(() => console.log('T2'), 0);
Answer: T1, P-in-T1, T2 — in browsers and in Node 11+. The microtask checkpoint runs after each task. Trap: answering T1 T2 P-in-T1, which was Node 10 and earlier, where microtasks were drained only between loop phases. Follow-up: What about process.nextTick in the first timer? It runs before the promise callback, still before T2.
Puzzle: Async function returns a rejected promise
async function boom() { throw new Error('x'); }
const p = boom();
console.log(p instanceof Promise);
p.catch((e) => console.log('caught', e.message));
console.log('after');
Answer: true, after, caught x. An async function never throws synchronously — the throw becomes a rejection, delivered in a microtask. Trap: wrapping boom() in a synchronous try/catch and expecting it to catch. Follow-up: When does Node report an unhandled rejection here if .catch is missing? After the microtask queue drains and the rejection still has no handler.
Puzzle: Generator values
function* gen() {
const x = yield 1;
const y = yield x + 1;
return x + y;
}
const it = gen();
console.log(it.next(10).value, it.next(20).value, it.next(30).value, it.next().done);
Answer: 1 21 50 true. The first next(10) starts the generator — its argument is discarded; next(20) resumes with x = 20 and yields 21; next(30) sets y = 30 and returns 50. Trap: thinking the first next argument becomes x. Follow-up: What does it.return(5) do mid-way? Finishes the generator with { value: 5, done: true }, running any finally blocks first.
Quick-Fire Questions
| Question | Answer |
|---|---|
What is NaN? | A number value meaning "not a number." typeof NaN === 'number'. Use Number.isNaN() to check. |
typeof null? | 'object' — a historical bug in JS that can never be fixed. |
0.1 + 0.2 === 0.3? | false — IEEE 754 floating-point precision. Use Math.abs(a - b) < Number.EPSILON. |
| What are symbols? | Unique, immutable primitive values used as object property keys to avoid collisions. |
What is globalThis? | The universal reference to the global object (window in browsers, global in Node.js). |
arguments vs rest params? | arguments is array-like, not a real array, not available in arrow functions. Rest (...args) gives a real array. |
| What is optional chaining? | obj?.prop?.method?.() — short-circuits to undefined if any link is nullish. |
| What is nullish coalescing? | a ?? b — returns b only if a is null or undefined (not 0, '', false). |
Object.freeze vs Object.seal? | freeze: no add/remove/change. seal: no add/remove, existing writable props can change. Both shallow. |
Object.hasOwn vs hasOwnProperty? | Object.hasOwn(obj, k) (ES2022) also works on null-prototype objects and can't be shadowed. |
| What is a tagged template? | tag`a${x}b` calls tag(['a', 'b'], x) — used for safe SQL/HTML builders and String.raw. |
Array.from vs spread? | Array.from also accepts array-likes ({ length: 3 }) and a map function; spread needs an iterable. |
Correction (2026-11-09): The
Number.EPSILONanswer for0.1 + 0.2only works for values near 1. For general magnitudes compare with a relative tolerance — see the floating-point question in Part 1.
Related Pages
- Dynamic Programming — Classic DP problems for coding interviews
- Arrays & Strings — Data structure fundamentals
- Trees — Binary tree traversal and manipulation
- React Interview Questions — Framework-specific questions
- Node.js Interview Questions — Server-side JavaScript questions
- Hash Tables — How
Mapand object property lookup work underneath - Regex Mastery — Regular expressions in depth, including
RegExp.escapeuse cases - TypeScript Cheat Sheet — Types on top of everything on this page