JS Interview Problems
Polyfills, async orchestration, and implementation questions frontend interviews actually ask. Spec-backed, with runnable JavaScript.
JavaScript Interview Learning Path
beginnerA frontend-shaped path through polyfills, async orchestration, output questions, and machine coding. Checkpoints you can implement, not course trophies.
beginner
Promise.all Polyfill
intermediateImplement Promise.all the way interviews score it: order-preserving results, fail-fast reject, and thenable wrapping with Promise.resolve.
intermediate
Promise.allSettled Polyfill
intermediateWrite Promise.allSettled as a status bag, not a silent all. Fulfilled and rejected entries, order, and why it never rejects for input failures.
intermediate
Promise.race Polyfill
intermediateImplement Promise.race: first settlement wins, including a fast rejection. Timeouts, cancellation myths, and the empty-iterable hang.
intermediate
Promise.any Polyfill
intermediateImplement Promise.any: first fulfillment wins, all-reject becomes AggregateError. Opposite of all, not a synonym for race.
intermediate
Promise.finally Polyfill
intermediatePolyfill Promise.prototype.finally: run cleanup on fulfill and reject, pass the original value through, and wait if the callback returns a thenable.
intermediate
Custom Promise From Scratch
advancedBuild a tiny Promise: executor, then chaining, microtask reactions, resolve-thenable unwrapping, and the states you are not allowed to leave.
advanced
Array.map Polyfill
beginnerImplement Array.prototype.map without cheating: thisArg, sparse holes, callback args, and why indexOf-based loops fail on duplicates and NaN.
beginner
Array.filter Polyfill
beginnerWrite filter that skips holes, respects thisArg, and never writes empty slots for rejected items. Contrast with map’s hole-preserving result.
beginner
Array.reduce Polyfill
intermediateImplement reduce with and without an initial value. Empty array TypeError, holes, left-fold order, and why skip-first-present-element is easy to get wrong.
intermediate
Array.flat Polyfill
intermediateImplement flat(depth) with Infinity, holes, and non-array array-likes. Recursion vs stack, and why concat(spread) blows up on huge inputs.
intermediate
Flatten a Nested Array
beginnerInterview flatten: stack vs recursion, depth cap, and treating only real arrays as nestable. Different problem from Array.flat polyfill details.
beginner
Flatten and Unflatten Objects
intermediateTurn nested objects into dot-path keys and back. Arrays vs objects, numeric keys, and why round-tripping `a.b[0]` is a product decision.
intermediate
Implement JSON.stringify
advancedA honest subset of JSON.stringify: primitives, arrays, objects, toJSON, skipped functions/undefined, and why cycles throw TypeError.
advanced
Implement the new Operator
intermediateWrite myNew(Ctor, ...args): create object, set prototype, call constructor, return object unless the constructor returned an object.
intermediate
Implement instanceof
intermediateWalk [[Prototype]] until you hit the constructor’s prototype. Symbol.hasInstance, primitives, and the null-prototype object that is nobody’s instance.
intermediate
Object.create Polyfill
beginnerImplement Object.create(proto, props): null prototype dictionaries, property descriptors, and why Object.create(undefined) is a TypeError.
beginner
Object.assign Polyfill
beginnerCopy enumerable own properties onto a target. Getters that run, symbols, null/undefined sources skipped, and the mutation-in-place return value.
beginner
Retry a Promise N Times
intermediateRetry an async function with a bounded count, delay, and a shouldRetry predicate. Do not retry 4xx you caused, and never hide the last error.
intermediate
Timeout a Promise
intermediateRace work against a timer without leaking the timer or pretending the work cancelled. withTimeout, clearTimeout, and why race is not AbortController.
intermediate
Run Async Tasks in Series
intermediateExecute async functions one after another, collect results in order, and stop on first rejection. Reduce vs for-await, and when series is the point.
intermediate
Run Async Tasks in Parallel
intermediateStart every task now, wait with Promise.all, and talk about the wall-clock vs series. Error handling and why unbounded parallel is a production bug.
intermediate
mapLimit: Async Map With a Concurrency Cap
advancedMap an array through an async iteratee with at most N in flight. Preserve output order, fail fast, and drain the queue without starving later items.
advanced
Infinite Currying in JavaScript
intermediateReturn a function until a sentinel (empty call or valueOf) asks for the sum. Closures, toString tricks, and why this is a closure test, not a math test.
intermediate
Method-Chaining Calculator
beginnerBuild a calculator object with add, subtract, multiply, divide, and a terminal value. Mutable this vs immutable copies, and divide-by-zero as an API choice.
beginner
Get and Set Nested Object Paths
intermediateImplement get(obj, path, fallback) and set(obj, path, value) for dot paths. Missing segments, non-object middles, and mutating vs cloning.
intermediate
Deep Equality in JavaScript
advancedCompare values structurally: primitives, NaN, arrays, plain objects, dates, and the cycle that will infinite-loop a naive recursion.
advanced
Implement groupBy
beginnerGroup array items by a key function or property name. Stable insertion of keys, and why mutating the source objects is a hostile API.
beginner
Chunk an Array
beginnerSplit an array into pieces of size n. Remainder chunk, size <= 0, and why splice in a loop mutates the input you were asked not to touch.
beginner
Implement Function Once
beginnerWrap a function so it runs at most once and then returns the first result. this, arguments, thrown errors, and async once that still shares the first promise.
beginner
Promisify a Node-Style Callback
intermediateTurn (err, value) callbacks into promises. Multiple success args, functions that already return thenables, and why you still need the original this.
intermediate
Cancelable Async Tasks
intermediateWrap work so a caller can abort: AbortController, ignored stale results, and the difference between cancelling IO and ignoring a resolved promise.
intermediate
Implement a Fake setTimeout
advancedA timer queue you can run in tests: schedule, clear, sort by due time, and flush without a real clock. Why a busy while-loop is a bad host.
advanced
Clear All Timeouts
intermediateTrack timer ids you created and clear them as a set. Monkey-patching the global is a test smell; a small TimerHost is the production shape.
intermediate
Arrays That Emit Change Events
advancedWrap push, pop, and splice so subscribers hear adds and removes. Proxy vs subclass, and why mutating via index assignment still slips through.
advanced
Walk the DOM Like getElementsByClassName
intermediateDFS or BFS a subtree for class tokens. Live vs static NodeList, classList vs className split, and why querySelectorAll is the modern answer.
intermediate
Serialize a Form to JSON
intermediateRead FormData, group duplicate names into arrays, skip disabled controls, and handle file inputs without pretending they are strings.
intermediate
Function.prototype.bind Polyfill
intermediateImplement Function.prototype.bind: bound this, prepended arguments, and new Bound() that still uses the original function prototype.
intermediate
Function.prototype.call and apply Polyfill
intermediatePolyfill call and apply: set this for one invocation, spread an argument list, and explain why apply(null, array) is not the same as a spread.
intermediate
Array.forEach Polyfill
beginnerImplement Array.prototype.forEach: visit present elements, skip holes, ignore the callback return, and honor thisArg without using native forEach.
beginner
Array.find Polyfill
beginnerWrite Array.prototype.find: first callback hit wins, holes are read as undefined, nothing matching returns undefined, and findIndex is the index twin.
beginner
Array.includes Polyfill
beginnerImplement Array.prototype.includes with SameValueZero: NaN is found, +0 equals -0, and fromIndex can walk backwards from the end.
beginner
Object.keys Polyfill
intermediatePolyfill Object.keys: own enumerable string keys in insertion order, no symbols, and integer-index keys listed before other strings.
intermediate
Object.entries and fromEntries
intermediateRound-trip own enumerable string keys with Object.entries and Object.fromEntries. Not a Map, not symbols, and later duplicate keys win.
intermediate
JSON.parse Implementation
advancedParse JSON with recursive descent, never eval. Why trailing commas throw, how strings and numbers tokenize, and where a reviver walks after.
advanced
Deep Clone Implementation
intermediateInterview deep clone: JSON is a lossy subset, structuredClone is the host, and recursion plus a WeakMap is how you survive cycles.
intermediate
Memoize Function
intermediateCache a function by arguments. Map keys vs JSON.stringify collisions, resolver functions, cache clear, and why this-bound methods need care.
intermediate
EventEmitter Implementation
intermediateBuild on, off, once, and emit. Copy the listener list before emit so a handler that unsubscribes cannot skip the next listener.
intermediate
Circuit Breaker in JavaScript
advancedClosed, open, half-open: stop calling a failing function, fail fast while open, and probe once when the cooldown expires.
advanced
Analytics SDK Event Queue
advancedQueue analytics events, send them in series, retry the ones that fail, and flush on page hide without dropping the last click.
advanced
localStorage with Expiry
beginnerWrap localStorage in a JSON envelope with expiresAt. Stale keys still occupy quota until you remove them, and JSON.parse can throw.
beginner
Async Filter Function
intermediateFilter an array with an async predicate: wait for every predicate, keep input order, emit a dense array, and decide fail-fast vs allSettled.
intermediate
mapSeries Async
intermediateMap one async iteratee at a time, preserve output order, fail fast on the first rejection, and contrast this with mapLimit worker pools.
intermediate
HTML Escape and Encode
beginnerReplace the five XML characters in user text. This is encoding, not a sanitizer, and innerHTML of escaped text is still the wrong default.
beginner
CSS Selector Generator
intermediateBuild a unique CSS path from a node to the root: id when unique, then nth-child among siblings, and stop before you invent a full query engine.
intermediate
In-Memory Filesystem
advancedmkdir, writeFile, readFile on a tree of maps. Normalize paths, reject escape via .., and decide whether writeFile creates parents.
advanced
Fetch Interceptors
intermediateWrap fetch so you can mutate the request, inspect the response, and chain interceptors, without monkey-patching window.fetch for the whole page.
intermediate