VIDHAIX / DEVELOPMENT / INTERVIEW PREP

Top 43 JavaScript Interview Questions & Answers (2026)

Closures, the event loop, promises, prototypes, modern ES features and output-prediction puzzles.

43 questions with answersUpdated 22 October 2026Reviewed by VidhaiX trainers

These JavaScript interview questions are for freshers preparing for their first developer role and for engineers with a few years of experience moving into product teams. JavaScript rounds rarely test trivia now. Service companies still open with scoping, hoisting and equality, but product companies and startups quickly move to the event loop, promise ordering, closures in real code, and asking you to implement something like `debounce` or `Promise.all` on a shared editor.

The questions are grouped into freshers, intermediate, experienced (3+ years) and scenario-based rounds, where you are handed a production problem and asked how you would debug it. Each answer explains what a strong response covers and where candidates usually lose marks. The set was compiled by VidhaiX trainers from the mock interviews we run with learners, and reflects the language as it stands in 2026, including recent additions such as `Object.groupBy`, Set methods and iterator helpers.

How to Prepare for a JavaScript Interview

  • Predict the console output of small snippets mixing `setTimeout`, promises, `await` and `queueMicrotask`, then run them in Node or the browser to check your reasoning.
  • Implement `debounce`, `throttle`, `Promise.all`, `Function.prototype.bind` and a deep clone from memory, including edge cases like empty input and rejected promises.
  • Explain closures and `this` with your own examples from a project instead of reciting definitions; interviewers follow up with what breaks when a method is passed as a callback.
  • Read the MDN pages for features added in the last two years (`toSorted`, `Object.groupBy`, `Promise.withResolvers`, Set methods, iterator helpers) and write one snippet using each.
  • Practise finding a memory leak with the Chrome DevTools Memory panel: take two heap snapshots, compare them, and trace a detached DOM node back to its retainer.
  • Build one small app with ES modules and no framework so you understand imports, the DOM event model and fetch without React or a bundler hiding the details.
  • Prepare two stories about async bugs you fixed, such as race conditions or unhandled rejections, covering how you found the cause and what you changed to prevent a repeat.

JavaScript Interview Questions for Freshers

12 questions

Q1.What is the difference between var, let and const, and what is the temporal dead zone?

var is function-scoped, can be redeclared, and is initialised to undefined when hoisted. let and const are block-scoped and are hoisted too, but stay uninitialised until their declaration line runs. The gap between entering the block and that line is the temporal dead zone, and reading the variable inside it throws a ReferenceError.

A common trap: const prevents reassignment of the binding, not mutation of the value. A const array can still be pushed to. Strong candidates say they default to const, use let when reassigning, and avoid var in new code.

js
console.log(a) // undefined: var is hoisted and initialised
console.log(b) // ReferenceError: cannot access 'b' before initialization
var a = 1
let b = 2

const list = [1]
list.push(2) // fine: the binding is constant, the array is not

Q2.What is hoisting, and how does it differ for function declarations and function expressions?

Before code in a scope runs, the engine registers every declaration in that scope. Function declarations are hoisted with their body, so you can call them above where they are written. A function expression assigned to a variable follows the variable's rules: with var you get undefined and a TypeError when calling it early, with let or const you hit the temporal dead zone.

A weak answer says code is physically moved to the top. Interviewers want to hear that it is a result of the creation phase of the execution context, and that classes are hoisted like let.

Q3.Explain == versus ===. Why does [] == false evaluate to true?

=== compares type and value with no conversion. == applies the abstract equality algorithm, which coerces operands: booleans become numbers, objects are converted to primitives via valueOf or toString. For [] == false, false becomes 0, the array becomes the empty string, which becomes 0, so the result is true.

Strong answers mention the one idiomatic use of ==: value == null matches both null and undefined. Otherwise use ===, and note that NaN is not equal to itself under either operator, so use Number.isNaN.

Q4.What is a closure? Give an example where you used one in real code.

A closure is a function bundled with references to the variables of the scope it was created in, so it can keep reading and updating them after the outer function has returned. The variables are captured by reference, not copied.

Good real-world examples: a debounce wrapper holding its timer id, a factory that creates API clients with a base URL, React hooks capturing props, or module-private state. Interviewers often follow up with the stale closure problem, where a callback keeps seeing an old value because it captured an earlier render or loop iteration.

Q5.How are primitives and objects passed to functions in JavaScript?

Everything is passed by value, but for objects the value is a reference. Primitives (string, number, bigint, boolean, undefined, null, symbol) are immutable, so a function can never change the caller's copy. For an object, the function receives a copy of the reference, so mutating a property is visible to the caller, while reassigning the parameter is not.

Candidates who say objects are passed by reference usually cannot explain why obj = {} inside a function leaves the caller unchanged. That distinction is exactly what is being tested.

Q6.What is the difference between null and undefined, and why does typeof null return object?

undefined means a value was never assigned: missing parameters, missing properties, functions without a return. null is an explicit, intentional absence that you assign yourself. JSON.stringify drops properties set to undefined but keeps null, which matters for API payloads.

typeof null === 'object' is a bug from the first implementation, kept for backward compatibility. To check for either value use value == null or the nullish operators ?? and ?., which, unlike ||, do not treat 0 or an empty string as missing.

Q7.How do arrow functions differ from regular functions?

Arrow functions do not have their own this, arguments, super or new.target; they take them from the enclosing scope. They cannot be used as constructors and have no prototype property. That makes them ideal for callbacks inside methods, where you want the outer this.

The trap is using an arrow function as an object method or prototype method and then finding this is not the object. Strong candidates also mention that class fields defined as arrows create a new function per instance, a small memory trade-off for automatic binding.

Q8.Which values are falsy, and how do optional chaining and nullish coalescing change everyday code?

The falsy values are false, 0, -0, 0n, '', null, undefined and NaN; everything else, including [] and {}, is truthy. Using || for defaults therefore replaces a legitimate 0 or empty string.

a ?? b falls back only when a is null or undefined. user?.address?.city short-circuits to undefined instead of throwing, and fn?.() calls only if the function exists. A good answer warns against chaining ?. everywhere: it can hide data bugs that should fail loudly.

Q9.Which array methods mutate the original array, and what are the non-mutating alternatives?

push, pop, shift, unshift, splice, sort, reverse and fill mutate in place. map, filter, slice, concat and reduce return new values. Since ES2023 there are copying versions: toSorted, toReversed, toSpliced and with(index, value).

This matters in React and Redux, where sorting state with sort() mutates it and the UI may not re-render. Interviewers also like to ask why [10, 9, 1].sort() gives [1, 10, 9]: the default comparator compares strings, so pass (a, b) => a - b for numbers.

Q10.What is event bubbling, and how does event delegation use it?

Most DOM events travel down from the window to the target (capture phase) and then back up (bubble phase). Event delegation attaches one listener to a common ancestor and uses event.target.closest() to work out which child was clicked.

Benefits: far fewer listeners, and elements added later are handled automatically. Strong answers mention the difference between target and currentTarget, that focus and blur do not bubble (use focusin and focusout), and that stopPropagation in a child silently breaks delegated handlers above it.

js
document.querySelector('#orders').addEventListener('click', (event) => {
  const button = event.target.closest('button[data-action]')
  if (!button || !event.currentTarget.contains(button)) return
  const row = button.closest('tr')
  handleAction(button.dataset.action, row.dataset.id)
})

Q11.What do the spread and rest operators do, and where can they surprise you?

The same ... syntax spreads an iterable or object into individual elements or properties, or collects remaining items into an array or object. Common uses: copying and merging objects, passing an array as arguments, and gathering extra function arguments with ...args.

The surprise is that spread copies only one level deep, so nested objects are still shared. Object spread also copies only own enumerable properties, ignores the prototype, and later keys overwrite earlier ones, which is handy for defaults like { ...defaults, ...options }.

Q12.What does 'use strict' change, and when is it on by default?

Strict mode turns silent failures into errors: assigning to undeclared variables throws, writing to read-only properties throws, duplicate parameter names are rejected, and this inside a plain function call is undefined instead of the global object. It also reserves some keywords and removes with.

You rarely write the directive today because ES modules and class bodies are strict automatically. A good answer connects this to this behaviour: code that worked in a classic script can break when moved into a module.

JavaScript Intermediate Interview Questions

12 questions

Q13.Explain the event loop. What is the difference between microtasks and macrotasks?

JavaScript runs on a single call stack. When it empties, the event loop drains the whole microtask queue (promise reactions, queueMicrotask, MutationObserver), then takes one macrotask (a timer, I/O callback, UI event), and in browsers may render before the next one. Microtasks queued during draining also run before the next macrotask.

Strong candidates can trace output order without guessing and know the consequence: an endless chain of microtasks starves rendering and timers. Mentioning Node's process.nextTick queue, which runs before promise microtasks, is a plus.

js
console.log('A')
setTimeout(() => console.log('B'), 0)
Promise.resolve().then(() => console.log('C'))
queueMicrotask(() => console.log('D'))
console.log('E')
// Output: A E C D B

Q14.How is the value of this decided when a function is called?

In priority order: called with new, this is the new object; called with call, apply or a function returned by bind, it is the supplied value; called as obj.method(), it is obj; a plain call gives undefined in strict mode or the global object in sloppy mode. Arrow functions ignore all of this and use the enclosing this.

The classic bug is passing obj.method as a callback, which loses the receiver. Fixes are bind, an arrow wrapper, or an arrow class field, and a good candidate can explain the trade-offs of each.

Q15.How does prototypal inheritance work, and what do ES classes add on top of it?

Every object has an internal link to a prototype. Property lookup walks this chain until it finds the key or reaches null. Methods live once on the prototype and are shared by all instances. Object.create(proto) creates objects with a chosen prototype directly.

Classes are mostly syntax over the same mechanism, but they add real features: they must be called with new, their bodies are strict, super works properly, and private #fields give true encapsulation rather than naming conventions. Weak answers stop at the syntax; interviewers want the lookup chain explained.

Q16.Compare Promise.all, Promise.allSettled, Promise.race and Promise.any.

Promise.all resolves with all results in input order and rejects as soon as one rejects. allSettled waits for every promise and returns status objects, useful for dashboards where partial data is fine. race settles with whichever settles first, success or failure, often used for timeouts. any resolves with the first success and rejects with an AggregateError only if all fail.

Key detail: none of these cancel the losing promises. The underlying requests keep running unless you pass an AbortSignal to them.

Q17.What goes wrong most often with async/await error handling?

The usual mistakes: forgetting await, so a rejection escapes the try/catch; using await inside forEach, which does not wait at all; awaiting independent calls one after another instead of with Promise.all; and swallowing errors with an empty catch.

A rejected promise nobody handles triggers unhandledrejection in browsers and, by default, crashes the process in modern Node. Strong answers mention return await inside try blocks so the error is caught locally, and wrapping errors with new Error(message, { cause }) to keep the original stack.

Q18.What is the difference between a shallow copy and a deep copy, and when would you use structuredClone?

A shallow copy ({ ...obj }, Array.from, Object.assign) duplicates the top level only; nested objects are shared. A deep copy duplicates the whole graph. structuredClone is built into browsers and Node, handles Date, Map, Set, typed arrays and circular references.

Its limits are worth stating: it throws on functions and DOM nodes, and class instances come back as plain objects. The JSON.parse(JSON.stringify()) trick loses dates, undefined, Map and Set, and fails on cycles.

js
const original = { when: new Date(), tags: new Set(['a']), nested: { n: 1 } }
const shallow = { ...original }
const deep = structuredClone(original)

shallow.nested.n = 2 // original.nested.n is now 2
deep.nested.n = 3 // original is unaffected
deep.when instanceof Date // true; a JSON round-trip gives a string

Q19.How do ES modules differ from CommonJS?

ES modules use import and export, are parsed statically so bundlers can tree-shake them, load asynchronously, support top-level await, and export live bindings. CommonJS uses require and module.exports, loads synchronously at runtime and exports a copy of the value at the time of assignment.

In Node, the type field in package.json or the .mjs and .cjs extensions decide the format. Modern Node versions can require() a synchronous ES module, but a module using top-level await still needs dynamic import(). Also mention that __dirname is replaced by import.meta.dirname in ESM.

Q20.What is the difference between debounce and throttle? Implement debounce.

Debounce delays a call until a burst of events has stopped for a set time, which suits search inputs and auto-save. Throttle runs at most once per interval during a continuous stream, which suits scroll and resize handlers or analytics pings.

In the implementation, interviewers check that you preserve this and arguments, clear the previous timer, and can discuss extensions: a leading-edge option, a cancel method, and flushing the pending call when a component unmounts.

js
function debounce(fn, wait) {
  let timer
  return function (...args) {
    clearTimeout(timer)
    timer = setTimeout(() => fn.apply(this, args), wait)
  }
}

const onSearch = debounce((query) => fetchResults(query), 300)

Q21.Implement a polyfill for Promise.all.

The essentials: return a new promise, accept any iterable, wrap each item with Promise.resolve so plain values work, store results by index rather than push order, count completions, and reject on the first failure. An empty input must resolve immediately with an empty array.

Candidates often push results as they arrive, which breaks ordering, or forget the empty case, which leaves the promise pending forever. Mention that later rejections after the first are ignored because a promise settles only once.

js
function promiseAll(iterable) {
  return new Promise((resolve, reject) => {
    const items = Array.from(iterable)
    const results = new Array(items.length)
    let remaining = items.length
    if (remaining === 0) return resolve(results)
    items.forEach((item, i) => {
      Promise.resolve(item).then((value) => {
        results[i] = value
        if (--remaining === 0) resolve(results)
      }, reject)
    })
  })
}

Q22.Write your own version of Function.prototype.bind.

A basic version returns a function that calls the original with a fixed this and pre-filled arguments via apply. A complete answer also handles new: when a bound function is used as a constructor, the bound this is ignored and the new instance is used, so the prototype chain must be preserved.

Interviewers use this to test whether you understand this rules, rest parameters and partial application together. Mention that native bound functions have no prototype and a name prefixed with bound, details a polyfill only approximates.

js
Function.prototype.myBind = function (thisArg, ...preset) {
  const fn = this
  function bound(...args) {
    const calledWithNew = this instanceof bound
    return fn.apply(calledWithNew ? this : thisArg, [...preset, ...args])
  }
  if (fn.prototype) bound.prototype = Object.create(fn.prototype)
  return bound
}

Q23.What does this loop print, and how do you fix it?

With var there is one i shared across all iterations, and by the time the timers fire the loop has finished, so it prints 3 three times. With let, each iteration gets a fresh binding, so the callbacks capture 0, 1 and 2.

Before let, the fix was an IIFE that captured the current value as a parameter. Interviewers use this question to check you understand closures capture variables, not values, and that the timers run only after the synchronous loop completes.

js
for (var i = 0; i < 3; i++) setTimeout(() => console.log(i))
// 3 3 3

for (let j = 0; j < 3; j++) setTimeout(() => console.log(j))
// 0 1 2

Q24.What are iterators and generators, and when would you write a generator?

An iterable has a Symbol.iterator method returning an iterator, an object whose next() returns { value, done }. for...of, spread and destructuring all use this protocol. A generator function (function*) produces such an iterator, pausing at each yield and resuming on the next call.

Generators fit lazy or infinite sequences, paginated API traversal, and walking trees without building an array. Async generators with for await...of are a clean way to consume streamed or paginated data. Good candidates note that generators are single-use once exhausted.

JavaScript Interview Questions for Experienced (3+ Years)

11 questions

Q25.What are the common causes of memory leaks in a JavaScript application, and how do you find them?

Typical culprits: event listeners and intervals never removed when a component unmounts, unbounded caches in module scope, closures keeping large objects alive, detached DOM nodes still referenced from JavaScript, and in Node, global maps keyed by request or listeners added per request.

The method matters more than the list. Reproduce the action several times, take heap snapshots before and after in Chrome DevTools or via node --inspect, compare them, and follow the retainer path to the root. Fix with AbortController signals for listeners, cleanup functions, and bounded or weak caches.

Q26.When would you use WeakMap, WeakSet or WeakRef?

WeakMap and WeakSet hold keys weakly: if nothing else references the key object, the entry can be garbage collected. That makes them right for attaching metadata or caching computed results per object or DOM node without causing leaks. They are not iterable and have no size, by design.

WeakRef and FinalizationRegistry give a weak reference to a value and a cleanup callback, but collection timing is unpredictable, so they suit only optional caches. A strong answer says you should rarely need them and must never rely on finalizers for correctness.

Q27.What is a Proxy, and where have you seen it used in practice?

A Proxy wraps an object and intercepts operations such as get, set, has and deleteProperty through trap functions. Reflect provides the default behaviour for each trap, so traps can add logic and then forward the call correctly, including the receiver.

Real uses: reactivity in Vue and MobX, immutable update helpers like Immer, validation, and test mocks. Trade-offs to mention: proxies add overhead on hot paths, identity checks differ from the target, and some built-ins with internal slots, such as Map or Date, break when proxied naively.

js
const user = new Proxy({}, {
  set(target, key, value, receiver) {
    if (key === 'age' && !Number.isInteger(value)) {
      throw new TypeError('age must be an integer')
    }
    return Reflect.set(target, key, value, receiver)
  },
})

Q28.Which recent additions to JavaScript do you actually use, and what problem does each solve?

Useful ones: toSorted, toReversed and with give immutable array updates without manual copying. findLast and findLastIndex search from the end. Object.groupBy and Map.groupBy replace hand-written reduce grouping. Promise.withResolvers returns a promise with its resolve and reject, tidier than capturing them from the executor when bridging event-based APIs.

Interviewers are checking whether you follow the language and can judge support. Mention checking browser targets or Node versions, and that Object.groupBy returns a null-prototype object.

js
const orders = [
  { id: 1, status: 'paid', amount: 500 },
  { id: 2, status: 'failed', amount: 200 },
  { id: 3, status: 'paid', amount: 900 },
]
const byStatus = Object.groupBy(orders, (o) => o.status)
const biggestFirst = orders.toSorted((a, b) => b.amount - a.amount)
const lastPaid = orders.findLast((o) => o.status === 'paid')
const { promise, resolve, reject } = Promise.withResolvers()

Q29.How do the new Set methods and iterator helpers change the way you write data transformations?

Sets now have union, intersection, difference, symmetricDifference, isSubsetOf, isSupersetOf and isDisjointFrom, replacing spread-and-filter code for permissions or tag comparisons. Iterator helpers add map, filter, take, drop, flatMap, reduce and toArray directly on iterators.

The important point is laziness: iterator helpers process one item at a time and stop early, so take(3) on an infinite generator works, and you avoid creating intermediate arrays for large data. Array methods remain eager.

js
const granted = new Set(['read', 'write'])
const required = new Set(['read', 'write', 'delete'])
required.difference(granted) // Set { 'delete' }
granted.isSubsetOf(required) // true

function* naturals() { let n = 1; while (true) yield n++ }
naturals().filter((n) => n % 2 === 0).map((n) => n * 10).take(3).toArray()
// [20, 40, 60]

Q30.How do you design error handling across a large JavaScript codebase?

Use custom error classes extending Error with a stable name or code, so callers can branch on type instead of parsing messages. Wrap lower-level errors with the cause option to keep context and the original stack. Handle errors at boundaries, such as route handlers, React error boundaries and job runners, rather than in every function.

Separate expected failures, like validation, from bugs. Register global handlers (unhandledrejection, process.on('uncaughtException')) for logging, not recovery, and send errors with context to a tool such as Sentry.

Q31.How would you run 500 async tasks with at most 5 running at a time?

Promise.all on 500 calls fires them all at once and can overwhelm an API or exhaust connections. A worker pool fixes this: start N workers that pull the next index from a shared counter until the list is exhausted, storing results by index.

Follow-ups to expect: what happens when one task fails (fail fast or collect errors with allSettled semantics), retries with backoff, and cancelling everything with an AbortSignal. Mentioning libraries like p-limit is fine, but you should be able to write it.

js
async function mapWithLimit(items, limit, worker) {
  const results = new Array(items.length)
  let next = 0
  async function run() {
    while (next < items.length) {
      const i = next++
      results[i] = await worker(items[i], i)
    }
  }
  const workers = Array.from({ length: Math.min(limit, items.length) }, run)
  await Promise.all(workers)
  return results
}

Q32.How do Object.is, ===, and SameValueZero differ, and where does it matter?

=== treats NaN as unequal to itself and 0 equal to -0. Object.is fixes both: Object.is(NaN, NaN) is true and Object.is(0, -0) is false. SameValueZero, used by includes, Map, and Set, treats NaN as equal to itself but 0 and -0 as equal.

This matters in practice: [NaN].indexOf(NaN) is -1 but [NaN].includes(NaN) is true. React uses Object.is to compare state and dependency arrays, which is why a new object or array every render always counts as a change.

Q33.A heavy computation is blocking the main thread. What are your options?

First measure with the Performance panel to confirm it is script time, not layout or rendering. Then choose: make the algorithm cheaper or memoise it; split the work into chunks and yield to the event loop between them so input and paint can run; or move it to a Web Worker, or a worker thread in Node, and pass data with transferable objects to avoid copies.

A weak answer says use async functions. Wrapping CPU-bound work in a promise does not move it off the main thread; it still blocks once it runs.

Q34.How do dynamic import, top-level await and tree shaking affect bundle size and load performance?

Dynamic import() returns a promise and creates a split point, so rarely used routes, editors or chart libraries load only when needed. Tree shaking removes unused exports, but only for static ESM imports and side-effect-free modules, so CommonJS dependencies and barrel files that re-export everything often defeat it.

Top-level await is convenient for configuration loading, but it blocks evaluation of every module that imports the awaiting one, so use it carefully in shared modules. Strong candidates verify claims with a bundle analyser.

Q35.Predict the output of this async snippet and explain each step.

Synchronous code runs first: 3, then calling f logs 1 synchronously because an async function runs until its first await. The await schedules the rest of f as a microtask. The then callback is queued as a second microtask, and 5 logs. The stack empties, microtasks run in order: 2, then 4.

The final order is 3, 1, 5, 2, 4. Candidates often assume an async function body runs entirely later, or that await null waits for a timer. Neither is true.

js
async function f() {
  console.log(1)
  await null
  console.log(2)
}
console.log(3)
f()
Promise.resolve().then(() => console.log(4))
console.log(5)

JavaScript Scenario-Based Interview Questions

8 questions

Q36.A search box shows results for an older query after the user finishes typing. How do you fix it?

This is a race condition: responses arrive out of order, and a slow response for an earlier query overwrites the latest one. Debouncing reduces the number of requests but does not fix ordering on its own.

The fix is to cancel stale requests with an AbortController before starting a new one, or to tag each request with an id and ignore responses that are not the latest. In React, do this in the effect cleanup. A strong answer covers both, and mentions handling the AbortError quietly instead of showing it to the user.

Q37.An internal dashboard tab gets slower and uses more memory the longer it stays open. How do you investigate?

Reproduce it with a repeatable action, such as switching between two views ten times, and watch the JS heap in the Performance monitor. If it keeps growing after a forced garbage collection, take heap snapshots before and after and use the comparison view.

Look for growing counts of detached DOM nodes, listeners, or arrays in a cache. Common causes on dashboards are setInterval polling never cleared, chart instances not destroyed on unmount, and websocket handlers registered on every render. Fix the cleanup, then rerun the same test to confirm.

Q38.The page freezes for several seconds when a user uploads a large CSV to be parsed in the browser. What do you do?

Parsing a big file synchronously on the main thread blocks input and painting. Move parsing into a Web Worker so the UI stays responsive, and stream the file with file.stream() or a streaming parser instead of reading it into one huge string.

Report progress back to the main thread with postMessage, and render results with virtualisation so you are not creating 100,000 table rows. Also question the design: if files are routinely huge, upload them and process on the server.

Q39.A Node.js service crashed in production with an unhandled promise rejection. What do you change?

First find the source from logs and the stack trace, often a promise started without await, a fire-and-forget call, or an event handler that is an async function whose rejection nobody observes. Fix the specific path by awaiting or handling it.

Then make it systemic: enable the no-floating-promises lint rule with type-aware linting, add a process.on('unhandledRejection') handler that logs with context and lets the process restart cleanly under the supervisor, and add a test for the failure path. Silently swallowing rejections to stop crashes is the wrong answer.

Q40.Editing a copy of a form state object also changes the original data shown elsewhere in the app. What is going on?

The copy was shallow. Spreading the top-level object copies references to nested objects and arrays, so editing draft.address.city mutates the shared address. Any component holding the original sees the change, and frameworks comparing references may not re-render at all.

Fixes: copy each level you change immutably, use structuredClone when you need an independent snapshot, or use a helper such as Immer. Strong candidates also suggest Object.freeze in development or a lint rule to catch accidental mutation early.

Q41.After upgrading a dependency, your build fails with ERR_REQUIRE_ESM. How do you resolve it?

The package is now ESM-only and your code loads it with require. Options, from best to worst: migrate your project to ESM by setting type to module and using import; load that one package with dynamic import(), which works from CommonJS; upgrade Node, since recent versions can require() ES modules that do not use top-level await; or pin the previous version temporarily.

A good answer checks the package's exports field and changelog, and considers the test runner and build tooling, which often need the same change.

Q42.A table with 5,000 rows has a click listener on every row and feels sluggish. How would you improve it?

Thousands of listeners cost memory and setup time, and re-rendering rows re-registers them. Replace them with one delegated listener on the table body that uses event.target.closest('tr') and a data-id attribute to find the row.

Then address the bigger problem: rendering 5,000 rows at all. Virtualise the list so only visible rows are in the DOM, or paginate. Measure before and after with the Performance panel, so you can show the improvement rather than assume it.

Q43.An invoice total shows 0.30000000000000004 instead of 0.3. How do you handle money correctly?

Numbers are IEEE 754 doubles, and many decimal fractions cannot be represented exactly, so 0.1 + 0.2 is not 0.3. Rounding at display time hides the symptom but errors still accumulate across line items, taxes and discounts.

Store and calculate money as integers in the smallest unit, such as paise, using BigInt if values can exceed Number.MAX_SAFE_INTEGER, or use a decimal library. Format only at the edge with Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' }), and agree rounding rules with the finance team.

From answers to offers

Prepare for JavaScript interviews with practicing engineers

If you want to use this JavaScript in real React and Node.js projects with code reviews from working engineers, the full-stack course takes you from fundamentals to a deployed application and mock interviews.