Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 77 ยท JavaScript Interview Questions

JavaScript: Classic Coding Questions

Write the classic JavaScript interview helpers from scratch: flatten, deep clone, memoize, a Promise.all polyfill and an event emitter, with tests you can run.

Many JavaScript interviews include a "write it yourself" round: implement flat, memoize, Promise.all or a tiny event emitter in 10 to 20 minutes. These tasks are popular because they are short, but they reveal how you handle recursion, closures, edge cases and asynchronous code.

For each question below you get a clear approach, a solution and tests that run in the editor. Work through them in this order every time: restate the requirements, pick the data structure, write the simplest version, then handle edge cases aloud. See Thinking Out Loud and Handling Hints for how to narrate this. The earlier lessons (closures, event loop, functional patterns) supply the building blocks.

Five questions you will meet

Flatten Recursion over nested arrays.
Deep clone Recursion plus cycles.
Memoize A closure with a cache.
Promise.all Counting async results.

Plus an event emitter, the pub/sub of the language.

1 / 2

1. Flatten a nested array

Task: turn [1, [2, [3, [4]]]] into [1, 2, 3, 4], with an optional depth. Built-in arr.flat(Infinity) exists, but interviewers want to see the recursion.

JS flatten with a depth limit

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Mention the edge cases: empty arrays, a depth of 0, and very deep nesting (recursion can overflow the call stack, so the iterative form is safer). Note that push(...bigArray) can also hit argument limits for huge arrays.

2. Deep clone

Task: copy an object tree so that changing the copy never changes the original. In real code you would call structuredClone (see the previous lesson); the exercise tests recursion and awareness of special values. Handle arrays, plain objects, dates, Map/Set, and circular references.

JS deepClone with cycle support

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The WeakMap is the interesting part: without it, a cycle causes infinite recursion. Say honestly what you skip (class instances with private fields, RegExp, typed arrays, getters), and that production code should use structuredClone.

3. Memoize

Task: write memoize(fn) that caches results by arguments. This is the standard closure question.

JS memoize with a cache key

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Discuss the limits of this version: JSON.stringify cannot tell undefined from null and fails on circular objects; the cache grows without bound (cap it, or use an LRU policy); and memoization is only safe for pure functions.

4. Polyfill Promise.all

Task: implement promiseAll(iterable) that resolves to an array of results in input order, and rejects as soon as any input rejects.

JS promiseAll and promiseRace

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Key details: wrap each item in Promise.resolve so plain values work; store by index so the order matches the input; handle the empty list; and use a counter rather than checking results.length, because assigning by index leaves holes.

5. Event emitter

Task: build a small pub/sub class with on, off, once and emit.

JS A minimal EventEmitter

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Talking points: copying the handler set before iterating, so that once and unsubscribing during emit do not skip handlers; using Set to avoid duplicates and give O(1) removal; and what you would add next (error events, prependListener, a maximum listener warning, async handlers).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does deepClone use a WeakMap?

    Remembering original-to-clone pairs stops infinite recursion on cycles and keeps shared references shared.
  2. 2. In promiseAll, why store each result at its original index?

    Promises finish in any order, but Promise.all must return values in the order of the input.
  3. 3. Which functions are safe to memoize?

    A cache returns an old result, which is only correct if the same arguments always give the same result.
  4. 4. Why does emit iterate over a copy of the handler set?

    Removing items from a collection while iterating it can skip entries. A snapshot keeps the current emit predictable.

Summary

  • Flatten with recursion (or a stack), and handle empty arrays and depth.
  • Deep clone needs a WeakMap for cycles and special cases for dates, maps and sets; prefer structuredClone in real code.
  • Memoize is a closure over a cache; the key function and cache size are the discussion points.
  • Promise helpers need Promise.resolve, index-based results and a counter.
  • An event emitter is a map from event names to sets of handlers.

Next: Python: Mutability, Identity and the Data Model.