24 role-specific questions
Node.js Developer Interview Questions & Answers
Node.js interviews focus on how the runtime handles concurrency, how you structure and secure an API, and how you deal with errors, streams and scaling in production.
Free, no sign-up. 107 questions in this role's practice pool, including behavioural, HR and situational questions.
Node.js interview questions
The Node.js runtime, async I/O, streams, Express, error handling and scaling.
1.
How does Node.js handle many concurrent requests on a single thread?
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Understanding non-blocking I/O and where Node struggles.
Key points a strong answer covers
- Non-blocking I/O. I/O is non-blocking: Node starts the operation and handles other work until it completes.
- Event loop / libuv. The event loop (libuv) dispatches callbacks when I/O completes.
- Thread pool. Some work (fs, crypto, DNS) uses libuv's thread pool.
- CPU-bound work blocks. CPU-heavy work blocks everyone — move it to worker threads or another service.
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 Node is multi-threaded for JavaScript code.
- Not knowing CPU-bound work blocks all requests.
Likely follow-up questions
- What happens to other requests if one request runs a 2-second loop?
- When would you use worker_threads?
Example strong answer
Node runs JavaScript on one thread, but almost all I/O is non-blocking. When a request needs the database, Node starts the query and moves on to other requests; when the result arrives, libuv's event loop queues the callback or resumes the awaiting function. Some operations — file system, crypto, DNS lookups — use libuv's small thread pool behind the scenes. This model handles thousands of concurrent I/O-bound connections cheaply. Its weakness is CPU-bound work: a heavy loop, image resizing or a big JSON parse blocks the single thread, so every other request waits. I move that to
worker_threads, a queue with separate workers, or another service.2.
How do you handle errors in a Node.js / Express application?
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Production robustness.
Key points a strong answer covers
- Async errors. Wrap awaits in try/catch, or let async errors reach the error middleware.
- Central error middleware. One error-handling middleware formats responses and logs.
- Operational vs programmer errors. Distinguish expected errors (validation, 404) from bugs.
- Process-level. Log unhandled rejections/exceptions and restart cleanly; don't keep running in a bad state.
- Don't leak details. Return safe messages and correct status codes; log details internally.
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
- Sending stack traces to clients.
- Swallowing errors with empty catch blocks.
Likely follow-up questions
- What should happen after an uncaughtException?
- How do Express 4 and 5 differ in async error handling?
Example strong answer
I separate expected, operational errors — invalid input, not found, a third-party timeout — from programmer errors, which are bugs. Expected errors become custom error classes with a status code. In Express, everything flows to one error-handling middleware with the
(err, req, res, next)signature, which logs the error with request context and returns a consistent JSON body without stack traces. Express 5 forwards rejected promises from async handlers automatically; in Express 4 I wrap handlers or use a helper. At process level I logunhandledRejectionanduncaughtException, then shut down gracefully and let the process manager restart, because the process may be in an unknown state.3.
What are streams in Node.js, and when would you use them?
AdvancedTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Handling large data efficiently.
Key points a strong answer covers
- Process data in chunks. Streams process data in chunks instead of loading everything into memory.
- Types. Readable, writable, duplex and transform streams.
- Backpressure. Backpressure stops a fast producer overwhelming a slow consumer.
- pipeline.
stream.pipelineconnects streams and handles errors and cleanup. - Use cases. Large files, uploads, CSV processing, compression, proxying.
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
- Reading a 2 GB file with readFile.
- Using .pipe without handling errors.
Likely follow-up questions
- What is backpressure, and how does Node handle it?
- Why prefer
pipelineover chaining.pipe()?
Example strong answer
Streams let you process data piece by piece instead of loading it all into memory. There are readable streams (a file being read, an HTTP request), writable ones (a file being written, a response), and duplex and transform streams, like gzip, that do both. If I need to export a 2 GB CSV, I read rows from the database as a stream, transform them to CSV, gzip them and pipe them into the HTTP response — memory stays flat. Streams handle backpressure: if the client downloads slowly, the writable signals it's full and the source pauses. I connect them with
stream.pipeline, which propagates errors and cleans up every stream, unlike chained.pipe()calls.4.
What is middleware in Express? Give examples.
BeginnerTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Basic Express architecture.
Key points a strong answer covers
- Function in the request chain. Middleware is a function that runs in the request pipeline with req, res and next.
- next(). It either ends the response or calls next() to continue.
- Order matters. Middleware runs in the order it's registered.
- Examples. Body parsing, logging, CORS, auth checks, rate limiting, security headers.
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
- Forgetting to call next(), leaving requests hanging.
- Registering the error handler before routes.
Likely follow-up questions
- How does error-handling middleware differ from normal middleware?
- How would you write middleware that times each request?
Example strong answer
Middleware in Express is a function with
(req, res, next)that runs as part of the request pipeline. It can read or modify the request, end the response, or callnext()to pass control on — if it does neither, the request hangs. Order matters because middleware runs in the order you register it. Typical examples:express.json()to parse bodies, CORS, Helmet for security headers, request logging, rate limiting, and an auth middleware that verifies the session and attachesreq.user, applied to protected routers. Error-handling middleware has four arguments,(err, req, res, next), and is registered last.5.
How would you scale a Node.js API?
AdvancedTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Production architecture beyond a single process.
Key points a strong answer covers
- Multiple processes. Run several processes or instances (cluster, PM2, containers) behind a load balancer.
- Stateless. Keep the app stateless; store sessions and shared state in Redis or a DB.
- Caching. Cache hot reads in Redis or at the CDN.
- Offload work. Move slow or heavy jobs to queues and workers.
- Database & measuring. Tune the database and connection pools; measure with metrics and load tests.
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
- Keeping sessions in memory and then adding more instances.
- Scaling the app when the database is the bottleneck.
Likely follow-up questions
- Why do in-memory sessions break when you add instances?
- How do you find the actual bottleneck?
Example strong answer
First I'd find the bottleneck with metrics and a load test, because often it's the database, not Node. Then: run several Node processes — one per core with the cluster module or PM2, or more realistically several containers — behind a load balancer. That requires the app to be stateless, so sessions, rate-limit counters and caches live in Redis rather than process memory. Hot reads get cached in Redis or at the CDN. Slow work like sending emails or generating PDFs moves to a queue such as BullMQ with separate workers, so requests return quickly. On the database side: indexes, a properly sized connection pool and read replicas if reads dominate.
6.
What security practices do you follow when building a Node.js API?
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Security hygiene for back-end JavaScript.
Key points a strong answer covers
- Validate input. Validate all input with a schema.
- Injection. Parameterised queries to prevent SQL/NoSQL injection.
- Auth & secrets. Hash passwords, keep secrets in env/secret managers, handle tokens carefully.
- Headers / rate limit. Helmet, strict CORS, HTTPS and rate limiting.
- Dependencies. Audit and update dependencies; lockfiles.
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
- Trusting client-side validation.
- Committing .env files with secrets.
Likely follow-up questions
- How do you protect a login endpoint from brute force?
- How do you handle a vulnerable transitive dependency?
Example strong answer
I validate every input at the edge with a schema like Zod, and never build queries by string concatenation — parameterised queries or an ORM prevent injection, including NoSQL operator injection. Passwords are hashed with bcrypt or Argon2. Secrets live in environment variables or a secrets manager, never in the repo. I add Helmet for security headers, a strict CORS allow-list, HTTPS, and rate limiting — especially on login and password-reset endpoints, plus account lockout or captcha after repeated failures. Error responses don't leak stack traces. And I keep dependencies under control: a lockfile,
npm auditand Dependabot in CI, and I review new packages before adding them.7.
When would you build a REST API versus a GraphQL API?
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
API design trade-offs.
Key points a strong answer covers
- REST resources. REST models resources with URLs and HTTP methods.
- GraphQL flexible queries. GraphQL lets clients request exactly the fields they need from one endpoint.
- Caching. REST benefits from HTTP caching; GraphQL caching needs more work.
- Complexity / N+1. GraphQL needs care with N+1 queries (DataLoader) and query cost limits.
- Choosing. GraphQL suits many clients with different needs; REST suits simpler or public APIs.
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 GraphQL is always faster.
- Ignoring caching and security implications.
Likely follow-up questions
- What's the N+1 problem in GraphQL and how does DataLoader help?
- How do you version each kind of API?
Example strong answer
REST models resources —
/orders/42— with HTTP methods and status codes. It's simple, widely understood, and works well with HTTP caching and CDNs, which makes it my default for public APIs and straightforward CRUD. GraphQL exposes one endpoint and a typed schema, and clients ask for exactly the fields they need, so a mobile screen gets everything in one request without over-fetching. That's valuable when many clients need different shapes of data. The costs: caching is harder, and you have to guard against N+1 queries — usually with DataLoader to batch lookups — and against expensive queries with depth or cost limits. So it depends on the clients and the team.8.
How do you test a Node.js API?
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Testing strategy for services.
Key points a strong answer covers
- Unit tests. Unit tests for business logic with Vitest, Jest or node:test.
- Integration / HTTP. Integration tests hit endpoints with Supertest.
- Real database. Use a real test database (e.g. Testcontainers) and reset data between tests.
- Mock external services. Mock external HTTP services, not your own code.
- CI. Run everything in CI on every pull request.
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
- Mocking the database so heavily that tests prove nothing.
- Tests that depend on each other's data.
Likely follow-up questions
- How do you keep tests isolated when they share a database?
- What would you mock, and what not?
Example strong answer
I use a mix. Business logic — price calculations, validation rules — gets fast unit tests with Vitest or
node:test. Most confidence comes from integration tests that call the real HTTP endpoints with Supertest against a real database, spun up with Docker or Testcontainers, with each test seeding its own data and rolling back or truncating afterwards so tests don't depend on each other. External services such as payment providers are mocked at the HTTP level with nock or MSW. Everything runs in CI on every pull request, and I look at coverage of important paths rather than chasing a percentage.9.
How do you manage configuration and secrets across environments in Node.js?
BeginnerTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Twelve-factor and operational basics.
Key points a strong answer covers
- Environment variables. Configuration comes from environment variables.
- Validate at startup. Validate config at startup and fail fast if something is missing.
- Secrets management. Secrets come from a secrets manager; .env files are never committed.
- Per environment. Same build, different config per environment.
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
- Hard-coding API keys.
- Reading process.env all over the codebase.
Likely follow-up questions
- Why validate configuration at startup?
- How would you rotate a leaked secret?
Example strong answer
Configuration comes from environment variables, so the same build runs in development, staging and production with different settings. Locally I use a
.envfile that's in.gitignore, with a committed.env.exampledocumenting the keys. I readprocess.envin one config module that validates everything with a schema at startup — ifDATABASE_URLis missing the app fails immediately with a clear message instead of crashing later. In production, secrets come from the platform's secret store or a manager like AWS Secrets Manager or Vault, never from the repo. If a secret leaks, I rotate it at the source first, then update the store and redeploy.10.
Sessions or JWTs for authentication in a Node.js app — how do you choose?
AdvancedTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Trade-offs in auth design.
Key points a strong answer covers
- Sessions are server state. Sessions store state server-side, with only an id in a cookie.
- JWTs are self-contained. JWTs are signed tokens carrying claims; servers verify without a lookup.
- Revocation. Sessions are easy to revoke; JWTs need short expiry plus refresh tokens or a deny-list.
- Storage. Keep either in an httpOnly cookie, not localStorage.
- Choice. Sessions suit a classic web app; JWTs suit distributed services or third-party APIs.
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 JWTs are encrypted.
- Using long-lived JWTs with no way to revoke them.
Likely follow-up questions
- How would you log a user out everywhere with JWTs?
- What goes in a JWT payload, and what shouldn't?
Example strong answer
With sessions, the server stores session data — in Redis or the database — and the browser just holds a random session id in an httpOnly cookie. Revoking is trivial: delete the session. A JWT is a signed token containing claims, so any service with the key can verify it without a lookup, which suits distributed systems and APIs used by third parties. The catch is revocation: a JWT is valid until it expires, so you use short-lived access tokens with refresh tokens, or a deny-list. JWTs are signed, not encrypted, so nothing sensitive goes in the payload. For a typical web app I'd use sessions in a secure cookie; for service-to-service auth, JWTs.
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 node.js developer mock interview, type or speak your answers, and get a score breakdown with what to improve.