JavaScript interview questions (2026): 20 answers on closures, event loop and modern ES
JavaScript interviews test exact runtime rules rather than framework trivia: what closures keep alive in memory, why microtasks drain before timers, how this and prototypes resolve at call time, and how to cancel or cap concurrent requests. Below are 20 questions grouped by level, with concise spoken answers and short code snippets verified in November 2026 against MDN Web Docs and the ECMA-262 specification.
On this page
What JavaScript interviewers actually test
Questions usually arrive in three formats: predicting execution order from spec rules, implementing utilities like debounce or a concurrency pool without libraries, and spotting async bugs or memory leaks in production code. Pair this guide with TypeScript interview questions, React interview questions, Angular interview questions and Node.js interview questions. Knowing the four Promise combinators cold prevents hesitation in live rounds:
| Combinator | Fulfills when | Rejects when | Typical use case |
|---|---|---|---|
Promise.all(iter) | All input promises fulfill | First rejection | Parallel fetches that are all required |
Promise.allSettled(iter) | All promises settle ({status, value|reason}) | Never rejects on input failures | Batch work or dashboards tolerating partial failure |
Promise.race(iter) | First settled promise fulfills | First settled promise rejects | Racing an operation against a deadline |
Promise.any(iter) | First promise fulfills | All reject (AggregateError) | Hedged reads across fallback mirrors |
Junior JavaScript interview questions
1. How do var, let and const differ in scope, hoisting and the Temporal Dead Zone?
var is function-scoped and initialized to undefined at scope entry. let and const are block-scoped ({ ... }) and hoisted uninitialized into the Temporal Dead Zone (TDZ) until their declaration line runs, throwing ReferenceError on early access (MDN: let). const locks the variable binding, not properties of an assigned object.
2. What is lexical scope, and what does a closure capture?
Lexical scope resolves variables by where a function was defined in source code. Every function forms a closure holding a live reference to its outer lexical environment — capturing bindings, not frozen copies. That is why for (let i = 0; i < 3; i++) gives each callback its own i, whereas var i shares one binding.
function createCounter(initial = 0) {
let count = initial;
return { increment: () => ++count, value: () => count };
}
const c = createCounter(10);
c.increment(); // 113. What is the difference between ==, === and Object.is()?
== (IsLooselyEqual) coerces types ("" == 0 is true). === (IsStrictlyEqual) never coerces and follows IEEE 754: NaN === NaN is false and +0 === -0 is true (MDN: Equality comparisons). Object.is() (SameValue) treats Object.is(NaN, NaN) as true and Object.is(+0, -0) as false; Set and Array.prototype.includes use SameValueZero.
4. Which values are falsy, and why prefer ?? over || for defaults?
Only false, 0, -0, 0n, "", null, undefined and NaN are falsy (plus browser legacy document.all); [] and {} are truthy. retries || 3 overwrites a valid 0, whereas nullish coalescing retries ?? 3 falls back only on null or undefined.
5. How is this determined in regular functions versus arrow functions?
Regular functions bind this at call time (MDN: this): new Fn() binds the instance, call/apply/bind set an explicit receiver, obj.fn() binds obj, and bare fn() gets undefined in strict mode (including modules and classes). Arrow functions have no own this and inherit it lexically from their enclosing scope.
const worker = {
prefix: "job",
run(ids) { return ids.map((id) => `${this.prefix}-${id}`); },
};
const detached = worker.run;
// detached([1]) throws TypeError in strict mode ('this' is undefined)6. How does structuredClone() beat shallow spread and JSON cloning?
Spread ({ ...obj }) copies only top-level properties, sharing nested references. JSON.parse(JSON.stringify(x)) drops undefined, stringifies Date, breaks Map/Set and fails on cycles. structuredClone() deep-copies nested graphs, cycles, Date, Map, Set and typed arrays natively, throwing DataCloneError on functions or DOM nodes.
7. Why use toSorted(), toSpliced(), with() and Object.groupBy()?
sort(), reverse() and splice() mutate arrays in place. Modern copying methods (toSorted(), toReversed(), toSpliced(), with()) return new arrays safely, and Object.groupBy(items, fn) groups iterables without reduce boilerplate. Always pass (a, b) => a - b when sorting numbers.
Mid-level JavaScript interview questions
8. How does the prototype chain work underneath ES classes?
Objects delegate property lookups up their internal [[Prototype]] link (Object.getPrototypeOf, Object.create) until reaching null (MDN: Prototype chain). ES class syntax uses the same prototype delegation while enforcing strict mode, non-enumerable methods, mandatory new and engine-enforced #private fields. Prefer Object.hasOwn(obj, key) over obj.hasOwnProperty.
9. In what order does the Event Loop run sync code, microtasks and macrotasks?
The engine finishes the current synchronous stack first, then drains the entire microtask queue (Promise.then/catch/finally, code after await, queueMicrotask, MutationObserver) — including newly queued microtasks — before running the next macrotask (setTimeout, I/O) or render frame (Execution model).
console.log("1");
setTimeout(() => console.log("6"), 0);
Promise.resolve().then(() => {
console.log("3");
queueMicrotask(() => console.log("5"));
});
(async () => { console.log("2"); await null; console.log("4"); })();
// Output: 1, 2, 3, 4, 5, 610. What happens to sibling requests when Promise.all rejects?
Promise.all rejects immediately on the first failure (MDN: Promise), but sibling promises keep running in the background unless cancelled via a shared AbortController. Use Promise.allSettled when you need every outcome.
11. Which async/await traps cause slowdowns or missed errors?
Awaiting independent calls inside for...of serializes network latency instead of using Promise.all; forEach(async () => ...) drops returned promises; and inside try/catch, writing return fetchUser(id) without await lets rejections bypass the local catch.
async function loadUserSafely(id) {
try {
return await fetchJson(`/api/users/${id}`); // await catches rejection locally
} catch {
return { id, fallback: true };
}
}12. How do you cancel fetch requests and listeners with AbortController?
AbortController passes controller.signal to fetch and addEventListener; calling abort() rejects pending fetches with AbortError and removes listeners at once. Combine caller cancellation and timeouts cleanly with AbortSignal.any and AbortSignal.timeout.
async function fetchWithDeadline(url, callerSignal, ms = 3000) {
const signal = callerSignal
? AbortSignal.any([callerSignal, AbortSignal.timeout(ms)])
: AbortSignal.timeout(ms);
const res = await fetch(url, { signal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}13. How do ES Modules differ from CommonJS?
ESM (import/export; MDN: Modules) resolves static module graphs ahead of execution — enabling tree-shaking and top-level await — and exports live read-only bindings. CommonJS (require/module.exports) loads synchronously at runtime and copies the exported reference at require time.
14. What is debounce versus throttle, and how do you implement debounce?
Debounce waits for a quiet gap of delay ms before firing once (search inputs, resize); throttle caps execution to once per interval ms during continuous events (scroll, drag).
function debounce(fn, delayMs) {
let timerId;
const wrapped = function (...args) {
clearTimeout(timerId);
timerId = setTimeout(() => fn.apply(this, args), delayMs);
};
wrapped.cancel = () => clearTimeout(timerId);
return wrapped;
}Senior JavaScript interview questions
15. Why does WeakMap prevent leaks where Map leaks, and why is it not iterable?
Map holds strong references to keys, keeping unused objects alive forever. WeakMap holds object keys weakly so key and value are garbage-collected once no external references remain, and omits iteration/.size so non-deterministic GC timing cannot affect program behavior. Prefer WeakMap over low-level WeakRef.
16. How do memory leaks happen in JavaScript, and how do you find them?
GC reclaims unreachable objects, not forgotten ones (MDN: Memory management). Common leaks are unremoved listeners or setInterval timers, unbounded module Map caches, and detached DOM subtrees retained by a JS reference to one child node. Compare two DevTools Heap Snapshots and filter for Detached nodes.
17. How do you cap concurrency when Promise.all is too wide?
Spawn Math.min(limit, items.length) workers pulling indices from a shared counter (race-free between synchronous steps) while preserving result order:
async function mapWithConcurrency(items, limit, mapper) {
const out = new Array(items.length);
let next = 0;
async function worker() {
while (next < items.length) { const i = next++; out[i] = await mapper(items[i], i); }
}
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
return out;
}18. When are generators and async iterators better than arrays?
function* yields lazily without allocating full arrays; async function* pairs with for await...of to pull paginated APIs or streams with automatic backpressure, stopping network calls immediately on break.
async function* fetchPages(startUrl) {
for (let url = startUrl; url; ) {
const page = await fetchWithDeadline(url);
yield* page.items;
url = page.nextCursorUrl ?? null;
}
}19. What bug does Reflect.get receiver fix inside a Proxy?
In a get(target, prop, receiver) trap, target[prop] runs getters on target with this bound to the raw object, skipping proxy tracking on nested reads. Reflect.get(target, prop, receiver) keeps this bound to the proxy. Watch out for hot-path overhead and #private field restrictions on proxies.
20. How do you keep the main thread responsive and block prototype pollution?
Keep main-thread tasks under 50 ms by yielding with scheduler.yield(), virtualizing long lists and offloading heavy CPU work to Web Workers with transferable ArrayBuffers. Prevent prototype pollution in recursive object merges by using Map or Object.create(null), checking Object.hasOwn and rejecting __proto__, constructor and prototype keys.
Where Interview Copilot fits
Interview Copilot is our desktop app for mock interviews and permitted live sessions. During practice it transcribes spoken JavaScript questions and surfaces key points — or acts as an AI coding interview assistant on coding problems — so you can rehearse crisp answers aloud. Always ask the recruiter beforehand what tools or references are allowed in a live round, and use it only when permitted. Try the free tier with 5 minutes of live recognition and 3 screenshot solutions free; Pro is $25 for one month as a one-time payment with no auto-renewal.
Sources
- MDN Web Docs — JavaScript
- ECMA-262 — ECMAScript Language Specification
- MDN — Closures
- MDN — let and Temporal Dead Zone
- MDN — Equality Comparisons and Sameness
- MDN — this
- MDN — Prototype Chain
- MDN — JavaScript Execution Model and Event Loop
- MDN — Promise
- MDN — AbortController
- MDN — structuredClone()
- MDN — Array.prototype.toSorted()
- MDN — Object.groupBy()
- MDN — JavaScript Modules
- MDN — WeakMap
- MDN — Memory Management
FAQ
What are the most common JavaScript interview questions in 2026?
Interviewers focus on closures and lexical scope, let and const versus var (the Temporal Dead Zone), strict equality versus Object.is, how this is bound in regular versus arrow functions, the event loop and microtask queue, Promise combinators, request cancellation with AbortController, structuredClone, non-mutating array helpers like toSorted, and debugging memory leaks.
Why do Promise callbacks run before setTimeout(..., 0)?
Promise reactions (.then, .catch, .finally and code resuming after await) are queued in the microtask queue, whereas setTimeout schedules a macrotask. After each task finishes on the call stack, the JavaScript runtime drains every queued microtask completely before picking the next macrotask.
What is the difference between Promise.all and Promise.allSettled?
Promise.all fulfills with an array of values only if every input promise fulfills, and rejects immediately as soon as any single promise rejects. Promise.allSettled waits for every promise to finish and always fulfills with status objects ({ status: 'fulfilled', value } or { status: 'rejected', reason }), making it ideal when partial results are useful.
When should I use Object.is() instead of ===?
Use === for almost all comparisons, and reach for Object.is() when NaN or signed zeroes matter: Object.is(NaN, NaN) returns true (whereas NaN === NaN is false) and Object.is(+0, -0) returns false (whereas +0 === -0 is true), which is why state-diffing libraries like React use Object.is.
How does WeakMap help prevent memory leaks in JavaScript?
A regular Map holds strong references to its object keys, keeping them in memory until explicitly deleted. A WeakMap holds object keys weakly, so once an object such as a removed DOM node has no other strong references, the garbage collector can reclaim both the key and its associated value automatically.
How do you cancel an in-flight fetch request in modern JavaScript?
Create an AbortController, pass controller.signal into fetch(url, { signal }), and call controller.abort() on cleanup or user navigation, which rejects the pending fetch with an AbortError. For simple deadlines, pass AbortSignal.timeout(ms) directly without manual setTimeout wiring.
More guides
Related articles
Read next
Use cases
Interview Copilot is a desktop app
It's a desktop app for macOS, Windows and Linux — a phone cannot capture the interviewer's audio or hide a window from screen share. Open this page on your computer to install it.
And during the interview this phone can be your screen: scan the QR code in the laptop app and the answers appear right here. How phone mode works →