JavaScript Interview Questions for Senior Developers — Closures, the Event Loop, Prototypes & Async (Deep Answers)
30 senior JavaScript interview questions with deep answers and real code: closures, the event loop, prototypes, async/await, memory leaks, and modules.
- Author
- Randhir Jassal
- Published
- Reading time
- 18 min read
- Views
- 46 views
Junior JavaScript interviews ask "what does
vardo." Senior interviews ask why all your click handlers log the same number, why aPromise.thenruns before asetTimeout(0), and why your single-page app's memory climbs until the tab crashes after an hour. JavaScript looks forgiving and turns out to be full of sharp edges — closures,this, the event loop, and the ways a long-lived SPA leaks memory — exactly where senior work lives. Seniority is knowing what the engine actually does, not just what the syntax says. This guide is 30 questions across scope & closures, this & prototypes, async & the event loop, and functional patterns, memory & modern JS.
Each answer is a short answer you could say in one breath, a deep dive into the mechanism (with code), and the senior signal the interviewer is listening for. Examples are grounded in Mattrx — a real multi-tenant marketing-analytics platform whose ReactJS frontend runs as a long-lived SPA, so memory, the event loop, and bundle size are daily concerns, not trivia. No Foo and Bar.
How to use this guide
Read the deep dive even when the short answer is obvious — seniority is in the why, the engine behavior, and the failure mode. The blocks build on each other. If you can predict each snippet's output out loud, you're ready.
Block A — scope, closures & types
1. var vs let vs const — what's actually different?
Short answer: var is function-scoped and hoisted (initialized undefined); let/const are block-scoped and live in the temporal dead zone until their declaration (accessing early throws). const binding can't be reassigned (the value can still mutate if it's an object). Default to const, use let when you must reassign, never var.
Deep dive: Block scoping is why let fixes the classic loop bug (Q3). The TDZ turns "used before declared" from a silent undefined into a loud ReferenceError.
Senior signal: You explain block scope + TDZ (not just "var is old"), and default to const for immovable bindings.
2. What is a closure, and why is it useful?
Short answer: A closure is a function that remembers the variables of the scope it was created in, even after that scope has returned. It's how JavaScript does private state, factory functions, memoization, and every hook/callback that "captures" a value.
Deep dive: The returned function keeps a live reference to the outer variables, not a copy.
// Private counter — `count` is unreachable except through the returned closures.
function makeCounter() {
let count = 0; // captured, kept alive by the closures below
return { inc: () => ++count, get: () => count };
}
const c = makeCounter();
c.inc(); c.inc(); c.get(); // 2 — `count` survives after makeCounter() returned
Senior signal: You describe closures as "captured live references to an outer scope" and can name real uses (private state, memoization, event handlers) — and you know they're also how leaks happen (Q27).
3. Why do all my loop handlers log the same number?
Short answer: With var, the loop variable is one function-scoped binding shared by every closure — by the time the handlers run, the loop has finished and they all read the final value. let creates a fresh binding per iteration, so each closure captures its own value.
Deep dive:
// BUG: var is function-scoped -> every handler closes over the SAME i (= n at click time).
for (var i = 0; i < buttons.length; i++)
buttons[i].onclick = () => console.log(i); // always logs buttons.length
// FIX: let is block-scoped -> a new binding each iteration.
for (let i = 0; i < buttons.length; i++)
buttons[i].onclick = () => console.log(i); // logs 0, 1, 2, ...
Senior signal: You explain it as one-shared-binding vs per-iteration-binding and reach for let (not an IIFE workaround) as the modern fix.
4. How does hoisting work?
Short answer: Declarations are processed before code runs. function declarations hoist fully (callable before their line). var hoists the binding but not the value (reads undefined early). let/const hoist into the TDZ (reads throw until the declaration). It's not "code moves up" — it's how the engine sets up scope.
Deep dive: This is why you can call a function foo(){} above its definition but not a const foo = () =>{}.
Senior signal: You distinguish function vs var vs let/const hoisting and frame it as scope setup, not literal code movement.
5. == vs === — and when is == ever okay?
Short answer: === compares value and type, no coercion. == coerces operands to a common type first, with famously surprising rules ('' == 0, null == undefined, [] == ![]). Default to ===. The one common == idiom: x == null to catch both null and undefined in one check.
Deep dive: Coercion bugs are silent; === makes intent explicit. Mattrx lints for == except the == null guard.
Senior signal: You default to ===, can name a coercion gotcha, and know x == null is the deliberate exception.
6. Primitives vs reference types — how are they passed?
Short answer: Primitives (number, string, boolean, null, undefined, symbol, bigint) are copied by value. Objects/arrays/functions are held by reference — the variable stores a reference, and passing it to a function copies the reference, so mutations inside are visible outside. JS is always pass-by-value; the value of an object is its reference.
Deep dive: This is why mutating a prop object inside a function surprises callers — and why React state must be replaced, not mutated.
Senior signal: You say "pass-by-value of a reference" precisely and connect it to accidental shared mutation.
7. null vs undefined vs NaN?
Short answer: undefined = a variable exists but has no value (uninitialized, missing arg/prop). null = an intentional "no value" you assigned. NaN = the result of an invalid numeric operation, and famously NaN !== NaN (use Number.isNaN). They're three different "empties."
Deep dive: Mattrx uses null for "known absent" (API returned no value) and treats undefined as "not set yet."
Senior signal: You separate intentional-absence (null) from not-set (undefined), and know NaN needs Number.isNaN, not ===.
8. How do you reliably check a value's type?
Short answer: typeof for primitives (but typeof null === 'object' is a historical bug), Array.isArray() for arrays, instanceof for class instances (fails across realms/iframes), and Object.prototype.toString.call(x) as the catch-all. No single operator covers everything.
Deep dive: typeof [] is 'object', so array checks need Array.isArray. Mattrx validates API payloads with explicit Array.isArray + typeof guards.
Senior signal: You know typeof null and typeof [] are traps and pick the right check per type rather than trusting typeof alone.
Block B — this, prototypes & objects
9. How is this determined?
Short answer: By the call site, not where the function is defined. Four rules, in priority: new (a fresh object), explicit call/apply/bind (the given object), implicit (obj.method() -> obj), and default (undefined in strict mode, else global). Arrow functions ignore all of this and inherit this from their enclosing scope.
Deep dive:
const dashboard = {
tenant: 'acme',
load() { return this.tenant; }, // implicit: this = dashboard
};
dashboard.load(); // 'acme'
const fn = dashboard.load;
fn(); // TypeError/undefined — `this` lost (bare call = default binding)
Senior signal: You say "call-site, not definition-site," recite the four rules by priority, and know arrow functions opt out.
10. Arrow functions vs regular functions?
Short answer: Arrows have no own this (lexical, inherited), no arguments, can't be newed, and have no prototype. Regular functions get this from the call site and have arguments. Use arrows for callbacks/closures where you want the surrounding this; use regular functions for methods and constructors.
Deep dive: In React, arrow callbacks are why you don't need .bind(this) anymore — the arrow closes over the component's scope.
Senior signal: You list the concrete differences (this/arguments/new/prototype) and pick per use case, not by habit.
11. What do call, apply, and bind do?
Short answer: All set this explicitly. call(thisArg, a, b) invokes now with args listed; apply(thisArg, [a, b]) invokes now with args as an array; bind(thisArg, ...) returns a new function with this (and any leading args) permanently fixed — it doesn't call.
Deep dive: bind is partial application for this — Mattrx uses it to pin a handler's context when passing it somewhere that would otherwise lose it.
Senior signal: You know call/apply invoke immediately (differing only in arg shape) while bind returns a bound function.
12. Explain prototypal inheritance and the prototype chain.
Short answer: Every object has a hidden link ([[Prototype]]) to another object. Property lookup walks this chain until found or it hits null. Objects inherit from other objects directly — there are no classes under the hood, just prototype links.
Deep dive: arr.map isn't on arr; it's found on Array.prototype up the chain. Adding to a prototype affects all instances (why you don't mutate built-in prototypes).
instance ---[[Prototype]]--> Campaign.prototype ---> Object.prototype ---> null
(own props) (shared methods) (toString, ...)
Senior signal: You describe lookup as walking the chain to null and know methods live on the prototype, shared across instances.
13. Is class real inheritance or just sugar?
Short answer: Syntactic sugar over prototypes. class gives cleaner syntax for constructors, methods (which go on the prototype), extends, and super — but under the hood it's still prototype links. It adds a few real things: methods are non-enumerable, and the body runs in strict mode.
Deep dive: extends sets up the prototype chain; super calls up it. Knowing it's prototypes explains why instance methods are shared, not copied per instance.
Senior signal: You call class sugar-over-prototypes but can name what it genuinely adds (non-enumerable methods, strict mode, clean super).
14. Shallow vs deep copy — how do you copy an object?
Short answer: Spread ({...obj}) and Object.assign are shallow — nested objects are still shared by reference. For a deep copy use structuredClone(obj) (built-in, handles cycles, Dates, Maps) — not the old JSON.parse(JSON.stringify(...)), which drops functions, undefined, and Dates.
Deep dive: The shallow-copy trap: you spread state, mutate a nested object, and accidentally mutate the original too. Mattrx uses structuredClone for true snapshots.
Senior signal: You know spread is shallow, reach for structuredClone, and can name what the JSON trick silently loses.
15. What does Object.freeze do (and its limits)?
Short answer: Object.freeze(obj) makes an object's own top-level properties non-writable and non-configurable — a shallow immutability. Nested objects stay mutable (you'd need a recursive "deep freeze"). It's runtime enforcement; TypeScript's readonly is compile-time only.
Deep dive: Freeze is shallow, so it guards the top level but not nested config objects.
Senior signal: You know freeze is shallow + runtime, distinct from TS readonly, and mention deep-freeze for nested structures.
16. What are getters/setters and property descriptors?
Short answer: Getters/setters (get/set) let a property run a function on read/write while looking like a field. Object.defineProperty controls a property's descriptor — writable, enumerable, configurable, or accessor functions — the low-level API behind them.
Deep dive: Descriptors are how you make a computed or read-only property, or hide one from for...in/JSON.stringify via enumerable: false.
Senior signal: You connect getters/setters to defineProperty descriptors and know enumerable/writable/configurable control visibility and mutability.
Block C — async & the event loop
17. Explain the event loop.
Short answer: JavaScript runs on one thread. Synchronous code runs on the call stack. When the stack empties, the event loop drains the microtask queue (Promises), then runs one macrotask (a setTimeout/I/O/UI callback), then drains microtasks again, and repeats. That's how single-threaded JS stays non-blocking.
Deep dive:
run sync code (call stack)
| (stack empty)
v
drain ALL microtasks (Promise .then, queueMicrotask) <- always fully drained first
|
v
run ONE macrotask (setTimeout, event, I/O)
|
+---> back to draining ALL microtasks -> next macrotask ...
Senior signal: You describe the stack -> drain-all-microtasks -> one-macrotask cycle, and stress that microtasks fully drain between macrotasks.
18. What prints first: setTimeout(0) or Promise.then?
Short answer: Promise.then. A resolved promise's callback is a microtask; setTimeout(0) is a macrotask. All microtasks run before the next macrotask, so the promise wins even with a 0ms timer.
Deep dive:
console.log('A');
setTimeout(() => console.log('B'), 0); // macrotask
Promise.resolve().then(() => console.log('C')); // microtask
console.log('D');
// Output: A D C B (sync -> microtasks -> macrotask)
Senior signal: You get the order right AND explain it by queue priority, not by "timers are slow."
19. Promises — states and error propagation?
Short answer: A promise is pending, then settles once to fulfilled or rejected (immutable after). .then chains transform the value; a rejection skips .then handlers and jumps to the next .catch. Returning a promise from .then flattens (no nesting). .finally runs either way.
Deep dive: One .catch at the end of a chain handles any rejection above it — that's why you don't need a catch per link.
Senior signal: You describe settle-once immutability and rejection-skips-to-catch propagation, and know returned promises flatten.
20. What does async/await desugar to, and how do you handle errors?
Short answer: async functions return a promise; await pauses the function until a promise settles, then resumes — it's promises with synchronous-looking syntax. Errors are handled with try/catch (a rejected awaited promise throws). An unawaited async call is a floating promise (unhandled rejection risk).
Deep dive:
async function loadKpis(tenantId) {
try {
const res = await fetch(`/api/kpis?t=${tenantId}`);
if (!res.ok) throw new Error(res.status); // rejects the returned promise
return await res.json();
} catch (e) {
logger.error('kpi load failed', e);
return null; // graceful fallback
}
}
Senior signal: You know async returns a promise, await = .then in disguise, and errors surface through try/catch; you flag floating (unawaited) promises.
21. Promise.all vs allSettled vs race vs any?
Short answer: all — resolves when all succeed, rejects on the first failure (fail-fast). allSettled — waits for all, never rejects, returns each status. race — settles as the first settles (success or failure). any — resolves on the first success, rejects only if all fail.
Deep dive: Mattrx loads several dashboard widgets with allSettled so one failing widget doesn't blank the whole dashboard.
Senior signal: You pick all for "need everything," allSettled for "independent, tolerate failures," and know race vs any differ on success-vs-any-settle.
22. What are the most common async mistakes?
Short answer: await in a loop when calls are independent (serial instead of parallel), forgetting to await/return a promise (floating), unhandled rejections, and mixing callbacks with promises. The big performance one is serial awaits that should be Promise.all.
Deep dive:
// SLOW: N serial round trips — each await blocks the next iteration.
for (const id of campaignIds) results.push(await fetchStats(id));
// FAST: fire all, await together — one wall-clock wait instead of N.
const results = await Promise.all(campaignIds.map(id => fetchStats(id)));
Senior signal: You spot serial-await-in-loop and parallelize it, and you never leave a promise unawaited by accident.
23. How do you convert a callback API to a promise?
Short answer: Wrap it in new Promise, calling resolve on success and reject on error inside the callback (or use util.promisify in Node). Then it composes with async/await and the combinators.
Deep dive:
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
await wait(300); // now awaitable
Senior signal: You know the new Promise((resolve, reject) => ...) bridge and reach for promisify rather than hand-rolling when available.
24. Implement debounce vs throttle — and when do you use each?
Short answer: Debounce delays running until activity stops for N ms (great for a search box — fire the API only after the user pauses). Throttle runs at most once per N ms during continuous activity (great for scroll/resize handlers).
Deep dive:
function debounce(fn, wait) {
let t;
return (...args) => { clearTimeout(t); t = setTimeout(() => fn(...args), wait); };
}
// Mattrx search: only hit /search after the user stops typing for 300ms.
const onSearch = debounce(q => fetchResults(q), 300);
Senior signal: You implement debounce correctly (reset the timer each call) and choose debounce-for-settling vs throttle-for-rate-limiting by the use case.
Block D — functional patterns, memory & modern JS
25. map / filter / reduce — and immutability in practice?
Short answer: map transforms each element (same length), filter selects a subset, reduce folds a list into a single value (sum, group, index). They return new arrays (immutable-friendly) instead of mutating — which is exactly what React state and predictable data flow need.
Deep dive:
// Group events by campaign in one pass — reduce as an aggregator.
const byCampaign = events.reduce((acc, e) => {
(acc[e.campaignId] ??= []).push(e);
return acc;
}, {});
Senior signal: You reach for reduce for aggregation/grouping, value the no-mutation return, and know when a plain loop is clearer than a clever reduce.
26. What are currying and function composition?
Short answer: Currying turns f(a, b, c) into f(a)(b)(c) — fixing arguments one at a time to build specialized functions. Composition chains small functions so the output of one feeds the next (compose(f, g)(x) = f(g(x))). Both come from treating functions as values.
Deep dive: Partial application (a cousin) pre-fills some args — e.g., a log curried with a fixed module name.
Senior signal: You explain currying as building specialized functions by fixing args and can compose small pure functions into a pipeline.
27. What causes memory leaks in a browser SPA, and how do you prevent them?
Short answer: Four classic causes: event listeners never removed, timers/intervals never cleared, closures that pin large objects, and detached DOM nodes still referenced by JS. In a long-lived SPA these accumulate across navigation until the tab bloats or crashes. Prevention: clean up in your component's unmount/useEffect return.
Deep dive: This is a real Mattrx concern — the dashboard runs for hours without a reload.
useEffect(() => {
const onResize = () => layout(data);
window.addEventListener('resize', onResize);
const timer = setInterval(poll, 5000);
return () => { // WITHOUT this cleanup, every mount leaks
window.removeEventListener('resize', onResize);
clearInterval(timer);
};
}, [data]);
Senior signal: You name the four leak sources, tie them to a long-lived SPA, and treat cleanup (removeEventListener/clearInterval/effect teardown) as mandatory, not optional.
28. ESM vs CommonJS, and why does it matter for bundle size?
Short answer: ESM (import/export) is static — the bundler can see exactly what's used and tree-shake the rest out. CommonJS (require) is dynamic, so it resists tree-shaking. ESM also enables dynamic import() for code-splitting — loading heavy code only when needed.
Deep dive: Mattrx lazy-loads heavy dashboard widgets via dynamic import() so the initial bundle stays small.
// Code-split: the charting lib ships only when the user opens the chart.
const Chart = React.lazy(() => import('./HeavyChart'));
Senior signal: You connect ESM's static structure to tree-shaking, and use dynamic import() to keep the initial bundle lean.
29. What are generators and iterators?
Short answer: An iterator is any object with a next() returning {value, done}; the iterable protocol (Symbol.iterator) is what for...of and spread consume. A generator (function* + yield) is a function that pauses and resumes, producing values lazily — a concise way to build iterators and lazy/infinite sequences.
Deep dive: async function* + for await...of streams async data (e.g., paged API results) without buffering all of it.
Senior signal: You distinguish the iterator protocol from generators, and know generators produce values lazily (and async generators stream).
30. What is event delegation and why use it?
Short answer: Instead of attaching a listener to every child, attach one listener to a common ancestor and use event.target to figure out which child fired — leveraging event bubbling. It means fewer listeners (less memory), and it handles elements added later automatically.
Deep dive: For a long list of rows, one delegated listener on the container beats N per-row listeners — fewer handlers to attach and clean up.
Senior signal: You explain delegation via bubbling + event.target, and cite fewer listeners + dynamic children as the wins.
Bonus — what makes an answer "senior" in JavaScript?
Short answer: A junior knows the syntax; a senior knows what the engine does — call-site this, the microtask/macrotask cycle, prototype lookup, and how a long-lived app leaks. "Why does this run in that order?" gets "I'm not sure" from a junior and "microtasks drain before the next macrotask, so the .then beats the setTimeout" from a senior.
Deep dive: The recurring senior lens across all 30: JavaScript's ergonomics hide real machinery. Predict output from the event loop, reason about this from the call site, prevent leaks by cleaning up, and keep bundles lean with ESM + dynamic import.
Senior signal: You reason from the engine's behavior (event loop, scope, prototypes), and you volunteer the failure mode — the leak, the coercion, the lost this — before you're asked.
The model to carry forward
JavaScript rewards people who know what's underneath: closures are live captures (and a leak source), this is decided at the call site, the event loop drains microtasks before macrotasks, prototypes back the class sugar, and a long-lived SPA survives only if you clean up listeners, timers, and references. Answer each question with the engine behavior and the failure it prevents, and you'll sound like someone who has shipped and debugged real JavaScript at scale — which is the signal.
Further reading
- React Interview Questions for Senior Developers — Hooks, Reconciliation, Fiber & Performance (Deep Answers)
- C# Interview Questions for Senior Developers — Async, Memory, LINQ & Concurrency (Deep Answers)
- ASP.NET Core Interview Questions for Senior Developers — Middleware, DI, Kestrel & Auth (Deep Answers)
Prepping for a senior frontend interview and want these drilled live, or a mock focused on the event loop and async? I'm always happy to help — reach me at randhir.jassal@gmail.com.
Get the next issue
A short, curated email with the newest posts and questions.