Key takeaways
- With 4–5 years of experience, rounds focus on async behaviour, closures,
this, prototypes, performance and writing utilities from scratch. - Expect at least one output-prediction puzzle (event loop) and one polyfill (bind,
Promise.all, debounce). - Senior frontend rounds add rendering performance, memory leaks, security (XSS/CSRF) and architecture questions.
At four or five years of experience, JavaScript interviews stop asking "what is a closure?" and start asking you to use closures, the event loop and prototypes to solve problems and explain production bugs. Here is what to prepare, with concise answers. For 100+ questions with runnable code, see the JavaScript interview questions guide.
Core language, at depth
Explain closures with a real use case you've shipped.
A closure is a function that remembers the variables from the scope where it was created, even after that scope has finished. Real uses: private state (module pattern), memoisation caches, event handlers that capture configuration, debounce/throttle, and React hooks (stale closures are a classic bug).
function createRateLimiter(limit, windowMs) {
let count = 0, start = Date.now(); // private state kept by the closure
return function allow() {
const now = Date.now();
if (now - start > windowMs) { start = now; count = 0; }
return ++count <= limit;
};
}How does prototypal inheritance work, and how do classes relate to it?
Every object has an internal [[Prototype]] link. Property lookup walks this chain until it finds the property or reaches null. class syntax is mostly sugar over constructor functions and prototypes, adding private fields (#x), static blocks and stricter semantics (classes always run in strict mode and must be called with new).
What is the difference between deep and shallow copy? How do you deep clone?
A shallow copy (spread, Object.assign) copies only the top level; nested objects are shared. For a deep copy, use structuredClone(), which handles Dates, Maps, Sets and circular references but not functions, DOM nodes or class prototypes. Avoid JSON.parse(JSON.stringify(x)) — it drops undefined, Dates and Maps.
What are WeakMap and WeakRef used for?
A WeakMap holds keys weakly, so when the key object becomes unreachable the entry can be garbage-collected. It is ideal for metadata or caches attached to objects (DOM nodes, for example) without causing leaks. WeakRef and FinalizationRegistry are advanced, non-deterministic tools — rarely needed in application code.
Async JavaScript
Predict the output, and explain why.
async function a() { console.log(1); await b(); console.log(2); }
async function b() { console.log(3); }
console.log(4);
setTimeout(() => console.log(5));
a();
Promise.resolve().then(() => console.log(6));
console.log(7);
// 4 1 3 7 2 6 5Synchronous code runs first: 4, then a() prints 1, then b() prints 3. await schedules the rest of a as a microtask, and the script continues to print 7. Microtasks then run in the order they were queued — the continuation of a (2), then the .then (6). The timer is a macrotask, so 5 comes last.
How do you handle errors with async/await and parallel requests?
Wrap await in try/catch. For parallel work, use Promise.all when every result is required (it fails fast on the first rejection), or Promise.allSettled when partial results are acceptable. Always add timeouts with AbortController, and never leave a promise floating without a catch.
const ac = new AbortController();
const timer = setTimeout(() => ac.abort(), 5000);
try {
const [user, orders] = await Promise.all([
fetch(`/api/user`, { signal: ac.signal }).then((r) => r.json()),
fetch(`/api/orders`, { signal: ac.signal }).then((r) => r.json()),
]);
} finally {
clearTimeout(timer);
}How would you cancel a stale request in a search box?
Debounce the input, and abort the previous request with an AbortController before starting a new one, so a slow old response can never overwrite newer results (a race condition).
Write it from scratch
Expect at least one of these in a live round. Practise until you can write each in under 5 minutes:
Function.prototype.bindpolyfillPromise.all/Promise.allSettleddebounceandthrottlecurryandmemoize- An
EventEmitterwithon,off,once,emit flattenfor nested arrays (with a depth parameter)- Deep equality
Function.prototype.myBind = function (ctx, ...preset) {
const fn = this;
return function bound(...args) {
// support `new bound()` — `this` is then the new instance
return fn.apply(this instanceof bound ? this : ctx, [...preset, ...args]);
};
};
function memoize(fn) {
const cache = new Map();
return (...args) => {
const key = JSON.stringify(args);
if (!cache.has(key)) cache.set(key, fn(...args));
return cache.get(key);
};
}Performance and the browser
What causes jank, and how do you find it?
Long tasks (over 50 ms) on the main thread block input and rendering. Layout thrashing — reading layout (offsetHeight) after writing styles inside a loop — forces synchronous reflows. Find these with the DevTools Performance panel and Web Vitals (INP, LCP, CLS). Fix them by splitting work (scheduler.yield() or setTimeout chunks), moving heavy computation to Web Workers, batching DOM reads and writes, and virtualising long lists.
How do you find a memory leak in a single-page app?
Repeat an action (open and close a modal ten times), take heap snapshots before and after, and compare them. Look for detached DOM trees and growing listener counts. The usual causes are listeners and intervals never removed on unmount, global caches, and closures capturing large objects.
How do you prevent XSS and CSRF?
XSS: never inject untrusted HTML (innerHTML, dangerouslySetInnerHTML) without sanitising it (DOMPurify), rely on framework escaping, and set a strict Content-Security-Policy. CSRF: use SameSite cookies, CSRF tokens for cookie-authenticated state changes, and verify Origin headers.
Architecture questions for senior roles
- How do you structure state in a large app (server state vs client state)?
- When would you choose server rendering vs client rendering vs static generation?
- How do you split bundles and lazy-load routes?
- How do you design a reusable component library with good accessibility?
- How do you migrate a large codebase to TypeScript incrementally?
Answer these with trade-offs and a real example from your work. Then go through the advanced JavaScript questions, the React interview questions, and test yourself with the JavaScript quiz.