Skip to content
FrontDepth, Home

Back to the topic

Practice: Memory leaks and garbage collection

Answer first, then compare. Rate yourself honestly — it drives your weak-areas list.

4 predict-output · 3 open

Questions up to level

Shows questions up to the selected level.

No practice questions for this level yet.

  1. Predict the outputJunior

    This is a simulation: a Map stands in for the browser's list of active intervals, and tick() fires every active interval once. A price panel is opened and closed three times, first without cleanup, then with it (and opened once more). What does it log?

    JavaScript
    const intervals = new Map();
    let nextId = 1;
    const startInterval = (fn) => {
      intervals.set(nextId, fn);
      return nextId++;
    };
    const stopInterval = (id) => intervals.delete(id);
    const tick = () => intervals.forEach((fn) => fn());
    
    let requests = 0;
    
    function mountPanel(withCleanup) {
      const id = startInterval(() => {
        requests += 1;
      });
      return withCleanup ? () => stopInterval(id) : () => {};
    }
    
    for (let visit = 1; visit <= 3; visit++) {
      const unmount = mountPanel(false);
      unmount();
    }
    tick();
    console.log(intervals.size);
    console.log(requests);
    
    intervals.clear();
    requests = 0;
    for (let visit = 1; visit <= 3; visit++) {
      const unmount = mountPanel(true);
      unmount();
    }
    mountPanel(true);
    tick();
    console.log(intervals.size);
    console.log(requests);
  2. Open questionJunior

    What is a memory leak in a garbage-collected language like JavaScript, and what usually causes it?

    Think it through first

    Answer out loud or in your head as if you were in an interview, then reveal.

  3. Predict the outputMiddle

    EventTarget, Event and AbortController behave the same in Node and in the browser. count() dispatches one resize event and returns how many listeners ran. What does it log?

    JavaScript
    const target = new EventTarget();
    let calls = 0;
    const onResize = () => {
      calls += 1;
    };
    const count = () => {
      calls = 0;
      target.dispatchEvent(new Event("resize"));
      return calls;
    };
    
    target.addEventListener("resize", onResize);
    target.addEventListener("resize", onResize);
    target.addEventListener("resize", () => {
      calls += 1;
    });
    console.log(count());
    
    const controller = new AbortController();
    target.addEventListener("resize", () => { calls += 1; }, { signal: controller.signal });
    target.addEventListener("resize", () => { calls += 1; }, { signal: controller.signal });
    console.log(count());
    
    controller.abort();
    console.log(count());
    
    target.removeEventListener("resize", onResize);
    target.removeEventListener("resize", () => {
      calls += 1;
    });
    console.log(count());
  4. Predict the outputMiddle

    A bounded cache built on Map insertion order (least recently used entry first). What does it log?

    JavaScript
    function createLru(limit) {
      const map = new Map();
      return {
        get(key) {
          if (!map.has(key)) return undefined;
          const value = map.get(key);
          map.delete(key);
          map.set(key, value);
          return value;
        },
        set(key, value) {
          map.delete(key);
          map.set(key, value);
          if (map.size > limit) map.delete(map.keys().next().value);
        },
        keys: () => [...map.keys()].join(","),
      };
    }
    
    const cache = createLru(2);
    cache.set("a", 1);
    cache.set("b", 2);
    cache.get("a");
    cache.set("c", 3);
    console.log(cache.keys());
    console.log(cache.get("b"));
    cache.set("a", 10);
    cache.set("d", 4);
    console.log(cache.keys());
    console.log(cache.get("a"));
  5. Open questionMiddle

    How does V8's garbage collector work, and why does it split the heap into generations?

    Think it through first

    Answer out loud or in your head as if you were in an interview, then reveal.

  6. Predict the outputSenior

    Nothing here depends on when the garbage collector runs — only on the WeakMap API. What does it log?

    JavaScript
    const meta = new WeakMap();
    const node = { id: 1 };
    
    meta.set(node, "seen");
    console.log(meta.get(node));
    console.log(meta.get({ id: 1 }));
    console.log("size" in meta);
    console.log(typeof meta.forEach);
    
    try {
      meta.set("user-1", "seen");
    } catch (error) {
      console.log(error.name);
    }
    
    meta.set(Symbol("local"), "ok");
    try {
      meta.set(Symbol.for("shared"), "seen");
    } catch (error) {
      console.log(error.name);
    }
    
    console.log(meta.delete(node));
    console.log(meta.has(node));
  7. Open questionSenior

    Users report that a single-page app gets slower after an hour of use. How do you find and fix the leak?

    Think it through first

    Answer out loud or in your head as if you were in an interview, then reveal.