Top 10 JavaScript scenario questions
Try each one yourself first, then open the model answer.
1. A loop using var creates click handlers that all report the last index. Why?
Show answerHide answer
var is function-scoped, so every handler closes over the same variable, which has its final value when clicked. Use let, which creates a new binding for each iteration.
2. The page freezes while processing a large array. How would you keep it responsive?
Show answerHide answer
JavaScript on the main thread blocks rendering. Move the work to a Web Worker, or split it into chunks and yield between them, for example with setTimeout or requestIdleCallback.
3. You use await inside forEach and the code after it runs before the work finishes. What is wrong?
Show answerHide answer
forEach ignores the promises returned by its callback. Use a for...of loop for sequential work, or await Promise.all over map for parallel work.
4. One of ten parallel requests fails and you lose all the results. What would you use instead?
Show answerHide answer
Promise.all rejects as soon as any promise rejects. Use Promise.allSettled and handle successes and failures separately.
5. A search box shows results for an older query after a newer one. How do you fix the race?
Show answerHide answer
Responses can arrive out of order. Cancel the previous request with AbortController, or tag each request and ignore any response that is not the latest. Debouncing input also reduces requests.
6. A single-page app gets slower the longer it stays open. How would you investigate?
Show answerHide answer
Suspect a memory leak: listeners, timers or subscriptions never removed, or caches that only grow. Compare heap snapshots in the browser developer tools and clean up when components are destroyed.
7. 0.1 + 0.2 !== 0.3 causes a wrong invoice total. What do you do?
Show answerHide answer
Numbers are binary floating point. For money, calculate in integer minor units such as cents, or use a decimal library, and format only for display.
8. Passing an object method as a callback makes `this` undefined. How do you solve it?
Show answerHide answer
`this` depends on how a function is called. Bind the method, wrap it in an arrow function, or define it as an arrow class field.
9. You must display user-submitted text on a page. How do you avoid cross-site scripting?
Show answerHide answer
Insert it as text with textContent or your framework's normal escaping, never as raw HTML. If HTML is required, sanitise it with a maintained library and add a Content Security Policy.
10. A setTimeout of 0 runs after a resolved promise callback. Why?
Show answerHide answer
Promise callbacks go into the microtask queue, which is emptied after the current script and before the next task. Timers are tasks, so they run later.
