Scenario-based JavaScript interview questions.
Scenario questions describe a product problem and ask what you would build: an API that fails half the time, a search box that fires too many requests, a list of uploads that must run four at a time. These are medium-level JavaScript questions drawn from real work, each with tests that check the edge cases interviewers ask about next.
7 of these questions have free answers; the rest are in Pro. Updated .
245
questions
- Medium
- 245
What interviewers look for
- You restate the scenario and its limits before writing code.
- You handle failure: timeouts, retries with backoff, cancellation and partial results.
- You keep the order of results and the number of requests under control.
- You can explain the trade-offs of your design and what you would test.
Concept questions, answered
The definitions and comparisons interviewers open with. Free to read, each with a full answer and examples.
How should a frontend retry failed HTTP requests?
Retry a request only when the failure is likely temporary (a network error, a timeout, 429, 502, 503 or 504) and only when repeating it is safe: GET, PUT and DELETE are idempotent, while POST needs an idempotency key. Wait longer between attempts with exponential backoff plus random jitter, respect Retry-After, cap the number of attempts, and stop when the user leaves or cancels.
Promise.all vs Promise.allSettled vs Promise.race vs Promise.any
All four take an iterable of promises and return one promise, but they decide differently. Promise.all fulfils when every input fulfils and rejects on the first failure. allSettled waits for all and never rejects. race copies the first promise to settle, either way. any fulfils with the first success and rejects only if all fail.
Async/await vs promises: what is the difference?
async/await is not a separate mechanism. It is syntax built on promises. An async function always returns a promise, and await pauses that function until a promise settles, then gives you its value or throws its error. The same work can be written either way. await mainly reads like synchronous code.
What is the event loop in JavaScript?
The event loop is how JavaScript runs asynchronous code on a single thread. Synchronous code runs on the call stack. When the stack is empty, the engine runs every queued microtask (promise callbacks, await continuations, queueMicrotask), the browser may render a frame, and then the loop takes the next task, such as a timer or a click, and repeats. That order is why a promise callback runs before setTimeout(fn, 0).
Cache-Control: no-cache vs no-store vs max-age=0
no-cache lets caches store the response but requires them to check with the server before every reuse. no-store forbids storing it anywhere. max-age=0 makes it stale immediately, so caches normally revalidate too, but unlike no-cache it still allows stale reuse in some cases, such as when the server is unreachable. Use no-store for sensitive data and no-cache for content that must always be current.
XMLHttpRequest vs fetch: what is the difference?
XMLHttpRequest (XHR) is the original event-based API for making HTTP requests from JavaScript. fetch is its modern, promise-based replacement: it works with async/await, streams response bodies, cancels with AbortController, and is the only option in service workers. Use fetch by default. XHR still has one practical advantage: built-in upload progress events.
Medium62
- Implement
curry()supporting partial applicationFreeImplement curry(fn). It returns a curried version of fn that keeps collecting arguments until it has at least fn.length… - Implement
compose()andpipe()Implement two helpers that chain functions: - Implement deep clone with circular references,
Map,Set, andDateImplement deepClone(value). It returns a copy where every nested object is new, so changing the copy never changes the… - Implement
memoize()with custom cache keysFreeImplement memoize(fn, resolver). It returns a function that caches the results of fn, so calling it again with the same… - Implement an EventEmitter with
on,off,emit, andonceImplement an EventEmitter class, similar to Node's: - Implement an LRU cacheImplement an LRUCache class with a fixed capacity. When it is full and a new key is added, it evicts the least recently…
- Implement an
EventTarget-style custom event systemThe DOM's EventTarget behaves differently from a Node-style emitter. Implement a small version of it without using the… - Implement
promisify()for callback-based APIsMany older APIs take a Node-style callback as their last argument: callback(error, result). Implement promisify(fn),… - Implement
asyncMap()preserving result orderImplement asyncMap(items, mapper). It calls the async mapper(item, index) for every item in parallel and returns a… - Implement
asyncFilter()with asynchronous predicatesarray.filter(async (x) => …) does not work: every async function returns a promise, and a promise is always truthy, so… - Implement
asyncReduce()with sequential executionImplement asyncReduce(items, reducer, initialValue). It works like Array.prototype.reduce, but the reducer(accumulator,… - Implement a
retry()utility supporting maximum attempts and delaysImplement retry(fn, { attempts = 3, delay = 0, shouldRetry = () => true } = {}). It calls the async fn(attempt) (attempt… - Implement mapLimit() / throttlePromises() with maximum N concurrent tasksFreeImplement mapLimit(items, limit, mapper). It calls the async mapper(item, index) for every item, but never runs more…
- Implement
promisePool()using worker loopsImplement promisePool(tasks, concurrency, { settle = false } = {}). tasks is an array of functions that each return a… - Implement an asynchronous task runner with configurable concurrencyImplement a TaskRunner class. Unlike a pool over a fixed list, tasks can be added at any time, and the concurrency can…
- Implement a priority-based task schedulerImplement a PriorityScheduler class. Tasks wait in a queue, and whenever a slot is free the highest-priority waiting…
- Implement a queue supporting pause, resume, and clearImplement a TaskQueue class that runs async tasks in order with a concurrency limit, and can be paused, resumed and…
- Implement a token-bucket API rate limiterFreeA token bucket holds up to capacity tokens and refills continuously at refillPerSecond tokens per second. Every request…
- Implement a sliding-window rate limiterImplement createSlidingWindowLimiter({ limit, windowMs, now = Date.now }). It allows at most limit requests per key in…
- Implement request deduplication for identical in-flight API callsThree components mount at the same time and each calls getUser(42). Without care, that is three identical network…
- Implement a concurrency-safe async cache with TTLFreeImplement createAsyncCache({ load, ttl, now = Date.now }). load(key) is an async function that fetches a value. The…
- Implement batch API calls with maximum batch size and intervalA product list renders 60 cards and each card asks for its price: getPrice(id). The API has a batch endpoint, POST…
- Write a deep
mergethat is safe from prototype pollutionConfig loaders, query-string parsers and "settings" endpoints often deep-merge user-controlled JSON into an object. A… - Escape HTML and sanitize URLs to close XSS holesA comment widget builds HTML strings from user input and has two cross-site scripting (XSS) holes: text is inserted raw,…
- Normalize nested API data into entities with memoized selectorsAn API returns posts with their authors and comments nested inside. The same user appears in many places, so updating…
- Implement an async mutex and a semaphoreTwo tabs of async code both read a value from IndexedDB, add to it and write it back. Sometimes an update disappears: a…
- Paginate an API with an async generator that cleans up on early
breakA cursor-paginated API is easiest to consume as a stream of items: for await (const user of paginate(fetchPage)) { ...… - Stream NDJSON from
fetchand handle rows split across chunksAn export endpoint returns 200,000 rows as NDJSON: one JSON object per line. Waiting for the whole body before showing… - Build a WebSocket client with reconnect, backoff, heartbeat and an offline send queueA raw WebSocket gives up on the first network blip, silently stays "open" on a dead connection, and throws if you send…
- Format ICU-style plural and select messages with
Intl."You have " + n + " message(s)" breaks in most languages: Polish has four plural forms, Arabic six, and Japanese one.…PluralRules - Find and fix three bugs in an async functionprocessOrders(orderIds, api) is supposed to:
- Parse a Server-Sent Events stream and resume with
Last-Event-IDEventSource cannot send an Authorization header or a POST body, so many apps read Server-Sent Events (SSE) with fetch… - Diagnose a failing CORS preflight and write the server's CORS handlerThe app on https://app.example.com calls the API on another origin:
- Choose
Cache-Controlheaders for hashed assets, HTML and API responsesAfter a deploy, some users see a blank page: their browser cached the old index.html, which points at JavaScript files… - Build a Mustache-style template engine with escaping and sectionsImplement render(template, data), a small logic-less template engine in the style of Mustache.
- Highlight search terms in text, merging overlapping matchesA search results page bolds the words the user searched for. Write highlight(text, queries), which returns an HTML…
- Build a small Zod-style schema validatorLibraries such as Zod validate API responses and form data against a schema written in code. Build a small version: an…
- Compose Koa-style async middleware with
next()Servers (Koa, Express), API clients and Redux all run a request through a chain of middleware. Implement… - Apply a JSON Patch (RFC 6902) without mutating the documentJSON Patch is a standard format for describing changes to a JSON document; APIs accept it in PATCH requests, and…
- Build a Superjson-style serializer for dates, maps, sets and BigIntsJSON.stringify loses types: dates become strings, Map and Set become {}, undefined disappears, NaN becomes null, and…
- Implement
cva()(class-variance-authority) for component variantsDesign systems built with Tailwind (shadcn/ui and many others) describe a component's styles with cva. Implement… - Build a mini test runner with
describe,it, hooks and timeoutsJest and Vitest feel like magic until you build one. Implement createTestRunner(), which returns { describe, it,… - Parse and write CSV with quoted fields, escaped quotes and newlines"Import from CSV" and "Export to CSV" buttons are everywhere, and line.split(",") breaks on the first address with a…
- Build a small state-machine library with guards, actions and subscriptionsUI flows (checkout, file upload, auth) are easier to get right as explicit state machines, which is what XState…
- Implement an immutability helper with
$set,$push,$mergeand$applyBefore Immer, React apps updated nested state with immutability-helper: a spec object that mirrors the shape of the data… - Build a time-travel key-value map that answers "what was the value at time t?"Feature flags, document versions and price histories all need "the value as of a moment". Implement a class HistoryMap.
- Build a chainable, immutable SQL query builder with safe parametersDrizzle, Knex and Prisma build SQL from chained method calls. Implement query(), which returns a builder:
- Build an in-memory key-value store with nested transactionsForm editors with "Cancel", game state with "undo this move" and optimistic UI all need transactions. Implement…
- Implement a binary-heap priority queue and merge k sorted listsSchedulers, "top N" lists and merging sorted feeds all need a priority queue, and JavaScript has none built in.…
- Build a feature-flag evaluator with targeting and stable percentage rolloutsLaunchDarkly, Statsig and GrowthBook all evaluate flags with the same core logic. Implement evaluate(flag, user),…
- Render a Markdown subset to safe HTMLComments, chat messages and READMEs are written in Markdown and shown as HTML. Implement markdownToHtml(markdown) for a…
- Implement
sleep()with cancellation and run async tasks in sequence"How do I wait in JavaScript?" and "how do I run promises one after another?" are two of the most searched async… - Protect a web app from CSRF with signed tokens, Origin checks and SameSite cookies"How do you prevent CSRF?" is one of the most common frontend security interview questions. Cookie-based sessions are…
- Calculate the difference between two dates: days, age and years-months-days"Difference between two dates in JavaScript" is one of the most searched date questions, and most answers on the web…
- Deep-diff two objects and apply the changes as a patch"Find the difference between two objects" comes up in interviews and in real work: undo history, "unsaved changes"…
- Use
ProxyandReflectfor validation, negative indexes, change tracking and read-only views"What is a Proxy and when would you use one?" usually turns into "write one". Proxy is how Vue 3 and MobX track state… - Write tagged template literals: an escaping
htmltag,dedentandString.Tagged templates power lit-html, styled-components, GraphQL's gql and safe SQL builders. Interviewers ask how they work…raw - Implement callback-style async helpers:
sequence(),parallel()andrace()Before promises, Node and browser code passed error-first callbacks: a function finishes by calling callback(error,… - Implement
LazyMan()with a chainable task queue:eat,sleepandsleepFirstLazyMan is a classic interview question about task queues. The calls in a chain only record what to do; the work runs… - Build Jest-style fake timers with
tick()andrunAll()to test debounce deterministicallyCode built on setTimeout (debounce, throttle, retry with backoff, polling) is slow and flaky to test with real time.… - Build an async.queue-style task queue and a two-at-a-time FIFO or LIFO callback queueFreeTwo versions of the same idea, a queue that runs only a few tasks at a time, have been reported in public interview…
- Work out when scripts run: classic,
async,defer, module and inline scripts against the parserFree"Where should the <script> tag go, and what do async and defer change?" is a standard question. Answer it precisely by…
Showing 62 of 245 medium questions. Browse the rest in the question bank
Practise with tests and full answers.
Every question has a runnable editor, tests and a step-by-step solution. Passes from ₹149, paid once; nothing renews.
Frequently asked
What are scenario-based JavaScript interview questions?
Questions that start from a real situation rather than a named function: limit how many requests run at once, retry a flaky API, cache responses that expire, cancel a search when the user types again, or batch analytics events. You choose the approach and write working code.
How should I answer a scenario-based question?
Repeat the problem back with its constraints, ask about edge cases such as errors, timeouts and ordering, sketch the approach, then code it. Finish by saying how you would test it and what you would change at a larger scale.
Are scenario-based questions asked to experienced developers?
Yes, mostly from two years of experience up. They replace puzzle questions in many SDE-2 and senior loops, because they show how you handle async code, failure and trade-offs.