14 role-specific questions
JavaScript Developer Interview Questions & Answers
JavaScript interviews probe the language itself: how scope and closures work, what the event loop does with your async code, how `this` and prototypes behave, and how you write robust code that handles errors and edge cases.
Free, no sign-up. 107 questions in this role's practice pool, including behavioural, HR and situational questions.
JavaScript interview questions
Closures, the event loop, async code, scope and the prototype chain — the core of every front-end and Node.js interview.
1.
Explain closures in JavaScript, with a practical example.
BeginnerTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Whether you understand lexical scope and can connect it to real code, not just recite a definition.
Key points a strong answer covers
- Function + outer scope. A closure is a function bundled with references to the variables of the scope it was created in.
- Variables stay alive. The captured variables live on after the outer function returns.
- Practical use. Private state, factories, memoisation, debounce/throttle and event handlers all rely on closures.
- Pitfall. Watch for stale values (e.g. in React effects),
varin loops, and accidentally retaining large objects.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Saying a closure is “a function inside a function” without explaining what it captures.
- No example — interviewers want to see you've used one.
Likely follow-up questions
- What does
for (var i = 0; i < 3; i++) setTimeout(() => console.log(i))print, and why? - How can a closure cause a memory leak?
Example strong answer
A closure is a function together with the variables from the scope where it was defined. Because the function keeps a reference to that scope, those variables stay alive even after the outer function has returned. A simple example is a counter factory:
makeCounter()declareslet count = 0and returns a function that increments it — each counter has its own privatecount. I use closures every day for event handlers, debounce helpers and module-private state. The main pitfall is stale values: a React effect or a timer can capture an old variable, so you need the right dependencies or a ref.2.
What is the event loop, and how do microtasks differ from macrotasks?
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Whether you can predict the order async code runs in, which matters for debugging race conditions and UI jank.
Key points a strong answer covers
- Single thread + call stack. JavaScript runs one call stack on a single thread; the event loop decides what runs next.
- Task queue. Timers, I/O and UI events queue (macro)tasks.
- Microtasks first. After each task, all queued microtasks (promise callbacks, await continuations) run before the next task.
- Rendering / blocking. Long synchronous work or endless microtasks block rendering.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Saying
setTimeout(fn, 0)runs immediately. - Forgetting that microtasks drain completely before the browser can paint.
Likely follow-up questions
- In what order do
console.log,setTimeoutandPromise.resolve().thenlog? - How would you break up a long-running loop so the page stays responsive?
Example strong answer
JavaScript runs on one thread with one call stack. The event loop takes the next task — a timer callback, an I/O completion or a UI event — and runs it to completion. After every task it drains the microtask queue, which holds promise reactions and
awaitcontinuations, and only then can the browser render and pick the next task. Soconsole.log('a'); setTimeout(() => log('b')); Promise.resolve().then(() => log('c')); log('d')prints a, d, c, b. In practice that's why a heavy synchronous loop freezes the UI; I split long work into chunks withsetTimeoutorscheduler.yield, or move it to a Web Worker.3.
What's the difference between var, let and const?
BeginnerTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Basic language fluency: scope, hoisting and immutability of bindings.
Key points a strong answer covers
- Function vs block scope.
varis function-scoped;letandconstare block-scoped. - Hoisting / TDZ. All are hoisted, but
varis initialised to undefined whilelet/constsit in the temporal dead zone until declared. - const binding, not value.
conststops reassignment, not mutation — a const object can still change. - Re-declaration.
varallows re-declaration in the same scope;let/constdon't.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Claiming
constmakes objects immutable. - Saying
letandconstaren't hoisted at all.
Likely follow-up questions
- How would you make an object truly read-only?
- Why does
varin a for-loop cause bugs with callbacks?
Example strong answer
varis function-scoped, can be re-declared, and is hoisted and initialised toundefined, so you can read it before the declaration line.letandconstare block-scoped; they're hoisted too, but they're in the temporal dead zone until the declaration runs, so early access throws.constprevents reassigning the binding, not changing the value —const user = {}can still get new properties; for a read-only object you'd useObject.freeze, which is shallow. In modern code I default toconst, useletwhen a value really changes, and avoidvar.- Function vs block scope.
4.
Explain promises and async/await. How do you handle errors and run requests in parallel?
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Practical async skills: error handling, sequencing and concurrency.
Key points a strong answer covers
- Promise states. A promise is pending, then fulfilled or rejected, once.
- async/await is syntax over promises. An async function returns a promise;
awaitpauses that function until the promise settles. - Error handling. Use try/catch around awaits (or
.catch), and never leave a rejection unhandled. - Parallel vs sequential. Awaiting in a loop is sequential;
Promise.allruns them together;allSettledwaits for every result.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Awaiting independent requests one by one, making the page slower.
- Using
Promise.allwithout considering that one rejection fails the whole batch.
Likely follow-up questions
- When would you choose
Promise.allSettledoverPromise.all? - How would you limit concurrency to five requests at a time?
Example strong answer
A promise represents a value that will arrive later; it's pending, then fulfilled or rejected exactly once.
async/awaitis syntax over promises: an async function always returns a promise, andawaitpauses just that function until the promise settles, so code reads top to bottom. For errors I wrap awaits in try/catch, or attach.catchwhen I'm not awaiting. If requests don't depend on each other I start them together withPromise.all, which rejects as soon as one fails; when I need every outcome — say, uploading ten files and reporting which failed — I usePromise.allSettled. For large batches I limit concurrency with a small pool.5.
How is the value of
thisdetermined in JavaScript?IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Whether you understand call-site binding — a frequent source of bugs in callbacks and classes.
Key points a strong answer covers
- Depends on the call.
thisis set by how a function is called, not where it's written. - Method / default binding.
obj.fn()sets this to obj; a plain call gives undefined in strict mode (the global object otherwise). - Explicit binding.
call,applyandbindsetthisexplicitly. - Arrow functions. Arrow functions don't have their own
this; they use the enclosing scope's. - new. With
new,thisis the newly created object.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Saying
thisrefers to the function itself. - Not knowing why a method loses
thiswhen passed as a callback.
Likely follow-up questions
- Why does
setTimeout(obj.method, 100)losethis, and how do you fix it? - When would you avoid an arrow function as an object method?
Example strong answer
thisis decided by the call, not the definition. Called as a method —user.greet()—thisisuser. Called as a plain function, it'sundefinedin strict mode or the global object otherwise.call,applyandbindset it explicitly, and withnewit's the newly created instance. Arrow functions don't bind their ownthis; they take it from the surrounding scope, which is why they're handy in callbacks inside class methods. A classic bug is passingobj.methodtosetTimeoutor an event listener: it's called without the object, sothisis lost — fix it withobj.method.bind(obj)or an arrow wrapper.- Depends on the call.
6.
Explain prototypal inheritance. How do ES6 classes relate to it?
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Depth of language knowledge beyond syntax.
Key points a strong answer covers
- Prototype chain. Objects link to a prototype; property lookups walk up the chain until found or null.
- Shared methods. Methods on the prototype are shared by all instances rather than copied.
- Classes are syntax.
classis mostly syntax over constructor functions and prototypes. - Creating links.
Object.create, constructor functions andextendsset up the prototype link.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Describing JavaScript classes as if they copy methods like Java classes.
- Confusing
prototype(on functions) with an object's internal prototype.
Likely follow-up questions
- What's the difference between
Foo.prototypeandObject.getPrototypeOf(foo)? - How does
hasOwnPropertydiffer from theinoperator?
Example strong answer
Every object has an internal link to another object, its prototype. When you read a property that isn't on the object itself, JavaScript looks it up on the prototype, then that object's prototype, and so on until it reaches
null. That's how inheritance works: methods live once on a prototype and every instance shares them. ES6 classes are largely syntax over this —class Admin extends UsersetsAdmin.prototype's prototype toUser.prototype, and methods in the class body go on the prototype. You can also link objects directly withObject.create(proto). Knowing this helps when debugginginstanceofor checking own properties withObject.hasOwn.7.
What is event delegation, and why is it useful?
BeginnerTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
DOM fundamentals and awareness of performance with many elements.
Key points a strong answer covers
- Bubbling. Most events bubble from the target up through its ancestors.
- One listener on a parent. Attach one listener to a common parent instead of one per child.
- Identify the target. Use
event.target.closest(selector)to find which child was clicked. - Benefits. Works for elements added later and uses fewer listeners.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Using
event.targetdirectly when the click lands on a nested icon inside the button. - Forgetting events like
focusdon't bubble (usefocusin).
Likely follow-up questions
- What's the difference between
event.targetandevent.currentTarget? - How do
stopPropagationandpreventDefaultdiffer?
Example strong answer
Events bubble: a click on a list item also fires on the list and every ancestor. Event delegation uses that by putting one listener on a parent — say the
<ul>of a long to-do list — and working out which child was clicked withevent.target.closest('li'). It means fewer listeners and it automatically handles items added later, which is ideal for tables or infinite lists. Two things to watch: useclosestbecause the target might be an icon inside the button, and some events such asfocusdon't bubble, so you'd usefocusininstead.8.
What's the difference between
==and===? What aboutObject.is?BeginnerTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Precision about type coercion.
Key points a strong answer covers
- Coercion.
==converts types before comparing;===doesn't. - Strict equality.
===requires the same type and value. - Edge cases.
null == undefinedis true;NaN === NaNis false; objects compare by reference. - Object.is.
Object.isis like===but treats NaN as equal to itself and +0/-0 as different.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Saying
==compares values and===compares references. - Not mentioning that objects are compared by reference with both.
Likely follow-up questions
- Why is
[] == falsetrue? - How would you compare two objects by their contents?
Example strong answer
===is strict equality: same type and same value, no conversion.==applies type coercion first, which produces surprises like'0' == falseand[] == falseboth being true. The one coercion I find genuinely useful isx == null, which catches both null and undefined. Objects and arrays are compared by reference with either operator, so two identical-looking objects aren't equal.Object.isis like===exceptObject.is(NaN, NaN)is true andObject.is(0, -0)is false. In code I use===by default and lint against==.- Coercion.
9.
What's the difference between debounce and throttle? When would you use each?
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Practical performance techniques for event-heavy UIs.
Key points a strong answer covers
- Debounce waits for a pause. Debounce runs once after events stop for a set time.
- Throttle limits rate. Throttle runs at most once per interval while events keep firing.
- Use cases. Debounce: search-as-you-type, autosave. Throttle: scroll, resize, mousemove.
- Implementation. Both are built with timers (and a closure holding the timer id).
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Mixing up which is which.
- Debouncing scroll position tracking so it only updates after the user stops.
Likely follow-up questions
- How would you implement debounce in a few lines?
- What does a leading-edge debounce do?
Example strong answer
Both limit how often a function runs during a burst of events. Debounce waits until the events stop for, say, 300 ms and then runs once — ideal for search-as-you-type so you send one request when the user pauses, or for autosave. Throttle runs at most once per interval while the events keep coming — good for scroll or resize handlers that need regular updates. Debounce is a closure holding a timer: each call clears the previous timeout and sets a new one. Throttle tracks the last run time or uses a timer flag. Where available,
requestAnimationFrameis often the best throttle for visual updates.10.
How do you copy an object in JavaScript? What's the difference between a shallow and a deep copy?
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Understanding of references and immutable update patterns.
Key points a strong answer covers
- Shallow copy. Spread and
Object.assigncopy only the top level; nested objects are still shared. - Deep copy. A deep copy duplicates nested objects too;
structuredClonedoes this natively. - JSON trick limits.
JSON.parse(JSON.stringify(x))loses dates, functions, undefined, Maps and cycles. - Why it matters. Accidental shared references cause state bugs, especially in React/Redux.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Thinking spread makes a full independent copy.
- Recommending the JSON trick without its limitations.
Likely follow-up questions
- What can't
structuredClonecopy? - How would you update a nested property immutably?
Example strong answer
Assigning an object just copies the reference. Spread (
{...obj}) andObject.assignmake a shallow copy: the top-level properties are new, but nested objects are still shared, so changingcopy.address.citychanges the original. For a deep copy I usestructuredClone, which handles nested objects, arrays, Dates, Maps and even cycles — but not functions or DOM nodes. The oldJSON.parse(JSON.stringify())trick loses dates, undefined and functions. In React state I usually don't deep copy at all; I copy just the path I'm changing, like{...user, address: {...user.address, city}}.- Shallow copy. Spread and
11.
Compare ES modules and CommonJS.
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Familiarity with tooling and how code is loaded in browsers and Node.
Key points a strong answer covers
- Syntax. ESM uses import/export; CommonJS uses require and module.exports.
- Static vs dynamic. ESM imports are static, enabling tree shaking; require is a runtime call.
- Loading. ESM loads asynchronously and supports top-level await; CommonJS loads synchronously.
- Interop. Node chooses via
"type": "module"or .mjs/.cjs; interop has rough edges.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Not knowing why tree shaking needs static imports.
- Ignoring that exports in ESM are live bindings.
Likely follow-up questions
- What is a dynamic
import()used for? - Why might a library ship both ESM and CommonJS builds?
Example strong answer
ES modules use
importandexport; CommonJS usesrequireandmodule.exports. ESM imports are static — they're resolved before the code runs — so bundlers can tree-shake unused exports, and the browser supports ESM natively.requireis an ordinary synchronous function call at runtime, which is flexible but harder to analyse. ESM loads asynchronously, supports top-level await and exports live bindings. In Node, the package's"type"field or the .mjs/.cjs extension decides which system a file uses. For code splitting I use dynamicimport(), which returns a promise.12.
How do memory leaks happen in a JavaScript application, and how would you find one?
AdvancedTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Debugging maturity on long-lived single-page apps.
Key points a strong answer covers
- Garbage collection basics. Memory is freed when objects become unreachable; leaks are unwanted references.
- Common causes. Forgotten listeners, intervals, subscriptions, growing caches, globals and detached DOM nodes.
- Tools. Compare heap snapshots in DevTools and look at retainers.
- Fixes. Clean up in teardown (effects' cleanup), use AbortController, WeakMap for caches.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Saying JavaScript can't leak because it's garbage collected.
- No method — guessing instead of measuring.
Likely follow-up questions
- What's a detached DOM node?
- How does
AbortControllerhelp clean up listeners?
Example strong answer
JavaScript is garbage collected, so a leak is really an unwanted reference that keeps objects reachable. Common causes in SPAs are event listeners or intervals that are never removed when a component unmounts, subscriptions that aren't cancelled, caches that only grow, and detached DOM nodes still referenced from JS. To find one I reproduce the action several times — open and close a modal ten times — take heap snapshots before and after in Chrome DevTools, and compare what's growing, then follow the retainers to the code holding it. Fixes are cleanup functions in effects,
AbortControllersignals for listeners and fetches, and WeakMap for object-keyed caches.13.
When would you use map, filter, reduce and forEach?
BeginnerTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Idiomatic, readable code and understanding of immutability.
Key points a strong answer covers
- map transforms.
mapreturns a new array of the same length with each item transformed. - filter selects.
filterreturns a new array with the items that pass a test. - reduce accumulates.
reducecombines items into one value — a total, an object, a group-by. - forEach for side effects.
forEachis for side effects and returns undefined; it can't be chained or broken out of.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Using
mapjust to loop (and ignoring the returned array). - Writing unreadable reduce calls when map + filter is clearer.
Likely follow-up questions
- How would you group an array of orders by customer?
- Which of these mutate the original array?
Example strong answer
maptransforms every item and returns a new array of the same length — turning API records into view models, for example.filterreturns the items that pass a test, like active users.reducefolds the array into one value: a sum, a lookup object, or grouping orders by customer.forEachis for side effects such as logging; it returns undefined and you can't break out of it. None of them mutate the original array, which suits React state. I prefer a readablefilterthenmapover a cleverreduce, and for very large data I'd use a single loop.- map transforms.
14.
Does
fetchreject on a 404 or 500 response? How do you handle HTTP errors properly?IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Real-world API handling and robustness.
Key points a strong answer covers
- Only network errors reject. fetch only rejects on network failures; HTTP errors still resolve.
- Check response.ok. Check
response.okor the status code and throw yourself. - Timeouts / aborts. Use AbortController (or
AbortSignal.timeout) for timeouts and cancellation. - User-facing handling. Parse the error body, show a useful message, and retry only safe requests.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Assuming a try/catch around fetch catches 500 errors.
- Never cancelling requests when a component unmounts.
Likely follow-up questions
- How would you add a 10-second timeout?
- Which requests is it safe to retry automatically?
Example strong answer
No —
fetchonly rejects for network-level failures such as DNS errors or the connection dropping. A 404 or 500 resolves normally, so I always checkresponse.ok(or the status) and throw an error with the status and the parsed error body. I wrap that in a small API helper so every call handles it the same way. For timeouts and cancellation I pass anAbortControllersignal —AbortSignal.timeout(10000)for a deadline, and aborting on unmount so stale responses don't update the UI. I'd only auto-retry idempotent requests like GETs, with backoff.
Ready to answer them out loud?
Run a timed javascript developer mock interview, type or speak your answers, and get a score breakdown with what to improve.