DEV Community

Cover image for 7 JavaScript interview questions where the follow-up decides the offer
Anaya Kapoor
Anaya Kapoor

Posted on AI-assisted

7 JavaScript interview questions where the follow-up decides the offer

You write debounce in four minutes. The interviewer nods, then asks:

"Nice. Now I need to cancel it when the component unmounts. And sometimes I need it to fire right now, before the user navigates away."

That second question is where the round is actually decided. The first answer shows you have seen the problem before. The follow-up shows whether you understand it.

Below are seven questions that come up again and again in frontend interviews, each with the first answer most people give, the follow-up that comes next, and code that holds up. Every snippet is plain JavaScript you can paste into a console.


1. Debounce, then "cancel it" and "fire it now"

The ask: delay calling a function until the user stops typing for wait ms.

The common first answer works, but loses this, has no way to cancel, and drops the last call if the page closes.

The follow-ups: keep this and the latest arguments, add cancel() for unmounts, add flush() to run the pending call immediately.

function debounce(fn, wait) {
  let timer = null;
  let lastArgs;
  let lastThis;

  function invoke() {
    timer = null;
    const args = lastArgs;
    const context = lastThis;
    lastArgs = lastThis = undefined;
    fn.apply(context, args);
  }

  function debounced(...args) {
    lastArgs = args;
    lastThis = this;
    clearTimeout(timer);
    timer = setTimeout(invoke, wait);
  }

  debounced.cancel = () => {
    clearTimeout(timer);
    timer = null;
    lastArgs = lastThis = undefined;
  };

  // Run the pending call now (for example before the user leaves the page).
  debounced.flush = () => {
    if (timer === null) return;
    clearTimeout(timer);
    invoke();
  };

  return debounced;
}
Enter fullscreen mode Exit fullscreen mode

What they are really checking: that you think about the lifecycle of the thing you built, not just the happy path. cancel is how you avoid calling setState on an unmounted component; flush is how you avoid losing the user's last keystroke.


2. Predict the output: the event loop

The ask: what does this print?

console.log("1");
setTimeout(() => console.log("2"), 0);
Promise.resolve().then(() => console.log("3"));
queueMicrotask(() => console.log("4"));
(async () => {
  console.log("5");
  await null;
  console.log("6");
})();
console.log("7");
Enter fullscreen mode Exit fullscreen mode

Answer: 1 5 7 3 4 6 2

Why:

  • 1, 5 and 7 are synchronous. The body of an async function runs synchronously until its first await, which is why 5 comes before 7.
  • 3, 4 and 6 are microtasks, queued in that order: the .then callback, then queueMicrotask, then the code after await.
  • 2 is a macrotask. Microtasks always drain completely before the next macrotask runs, so setTimeout(..., 0) comes last.

The follow-up: "What happens if a microtask keeps queueing more microtasks?" The macrotask never runs and the page freezes, because the microtask queue must be empty before the browser can render or run timers. That is the one-line answer that separates "memorised the order" from "understands the loop".


3. Promise.all from scratch, then the edge cases

The ask: implement Promise.all.

The follow-ups are all edge cases, and they are where most implementations fail:

  1. Results must keep the input order, not the order promises settle in.
  2. An empty array must resolve immediately with [].
  3. Plain values (not promises) are allowed in the input.
  4. The first rejection rejects the whole thing.
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) {
      resolve(results);
      return;
    }

    items.forEach((item, index) => {
      // Promise.resolve wraps plain values, so 42 works like a promise.
      Promise.resolve(item).then((value) => {
        results[index] = value; // by index, so order matches the input
        remaining -= 1;
        if (remaining === 0) resolve(results);
      }, reject);
    });
  });
}
Enter fullscreen mode Exit fullscreen mode

A common bug is results.push(value): it passes a quick test and returns results in the wrong order as soon as one promise is slower than another.


4. Run async tasks with a concurrency limit

This one shows up a lot in mid-level and senior rounds, because it is a real production problem: upload 200 files, but never more than 3 at a time.

The ask: mapLimit(items, limit, fn) runs fn on every item, at most limit at once, and returns results in input order.

async function mapLimit(items, limit, fn) {
  const results = new Array(items.length);
  let next = 0;

  // Each worker takes the next index until none are left.
  async function worker() {
    while (next < items.length) {
      const index = next++;
      results[index] = await fn(items[index], index);
    }
  }

  const workers = Array.from({ length: Math.min(limit, items.length) }, worker);
  await Promise.all(workers);
  return results;
}

// Usage
const pages = await mapLimit(urls, 3, (url) => fetch(url).then((r) => r.text()));
Enter fullscreen mode Exit fullscreen mode

Why it works: JavaScript is single-threaded, so next++ can never be read by two workers at once. No locks needed.

The follow-up: "If one request fails, the others keep running. How do you stop them?" Pass an AbortController's signal into fn, call abort() in a catch, and check signal.aborted before a worker picks up the next item. Interviewers love this because it shows you know cancellation is not automatic in JavaScript.


5. Memoize, then "what's your cache key?" and "won't this leak?"

The common first answer stores results in an object keyed by the first argument. The follow-ups break it immediately:

  • What about multiple arguments? Or objects as arguments?
  • The cache grows forever. On a long-lived page that's a memory leak.
function memoize(fn, { key = (...args) => JSON.stringify(args), max = 500 } = {}) {
  const cache = new Map();

  return function memoized(...args) {
    const k = key(...args);

    if (cache.has(k)) {
      // Move to the end, so the least recently used entry is always first.
      const value = cache.get(k);
      cache.delete(k);
      cache.set(k, value);
      return value;
    }

    const value = fn.apply(this, args);
    cache.set(k, value);

    // Map keeps insertion order, so the first key is the oldest: evict it.
    if (cache.size > max) cache.delete(cache.keys().next().value);
    return value;
  };
}
Enter fullscreen mode Exit fullscreen mode

Things worth saying out loud in the interview:

  • JSON.stringify is a reasonable default key, but it treats {a:1,b:2} and {b:2,a:1} as different and drops functions and undefined. That's why the key function is configurable.
  • If fn is async and the promise rejects, you probably don't want to cache the failure forever. Delete the entry in a .catch.

6. Function.prototype.bind, then "what if I call it with new?"

The ask: write your own bind with partial application.

Most answers handle this and preset arguments. The follow-up is: "What should new boundFn() do?" With the native bind, new ignores the bound this and constructs a new instance of the original function.

Function.prototype.myBind = function (thisArg, ...preset) {
  const fn = this;

  return function bound(...args) {
    // Called with `new`: construct the original function, ignore thisArg.
    if (new.target) return new fn(...preset, ...args);
    return fn.apply(thisArg, [...preset, ...args]);
  };
};

function Point(x, y) {
  this.x = x;
  this.y = y;
}

const PointAtX5 = Point.myBind(null, 5);
const p = new PointAtX5(10);
console.log(p.x, p.y, p instanceof Point); // 5 10 true
Enter fullscreen mode Exit fullscreen mode

new.target is the detail that impresses here: it tells you whether the function was called with new, without any instanceof tricks.


7. React: a setInterval that doesn't go stale

The ask: a counter that ticks every second with setInterval inside useEffect.

The common first answer:

useEffect(() => {
  const id = setInterval(() => setCount(count + 1), 1000);
  return () => clearInterval(id);
}, []); // count is captured once: the counter gets stuck at 1
Enter fullscreen mode Exit fullscreen mode

The callback closes over the first render's count, so it sets 0 + 1 forever. Adding count to the dependency array "fixes" it by tearing down and recreating the interval every second, which drifts.

The follow-up answer is a hook that keeps the interval stable and the callback fresh:

function useInterval(callback, delay) {
  const saved = useRef(callback);

  // Always point at the latest callback, without restarting the timer.
  useEffect(() => {
    saved.current = callback;
  });

  useEffect(() => {
    if (delay === null) return; // null pauses the interval
    const id = setInterval(() => saved.current(), delay);
    return () => clearInterval(id);
  }, [delay]);
}

// Usage
useInterval(() => setCount((c) => c + 1), running ? 1000 : null);
Enter fullscreen mode Exit fullscreen mode

Explaining why the first version gets stuck (closures capture a render's values) is worth more than the fix itself.


The pattern

Look at what the follow-ups have in common:

  • Lifecycle: cancel, flush, cleanup, abort.
  • Edge cases: empty input, plain values, order, new.
  • Cost: memory that grows forever, intervals that restart every tick.

When you practise, don't stop at "it works". Ask yourself the next question an interviewer would ask, and make your code answer it.


Practise these with real tests

I built UIRound around this idea: the first answer gets you started, the follow-up gets you the offer. Every question there runs in a browser editor against real tests, and each answer walks through the follow-ups interviewers ask next.

All seven questions above are free to solve there, with tests:

  1. Debounce with cancel and flush
  2. Predict the event loop order
  3. Promise.all from scratch
  4. mapLimit with a maximum of N at once
  5. Memoize with custom cache keys
  6. Function.prototype.bind with partial application
  7. useInterval without stale closures

Which follow-up has caught you out in an interview? Tell me in the comments and I'll write up the best answer.

Top comments (0)