MediumClosures & Scope🐛 Debug Challenge

Shared memoize cache across all functions

Buggy Code — Can you spot the issue?

const cache = {};

function memoize(fn) {
  return function(...args) {
    const key = JSON.stringify(args);
    if (key in cache) return cache[key];
    cache[key] = fn(...args);
    return cache[key];
  };
}

const double = memoize(x => x * 2);
const triple = memoize(x => x * 3);

double(5);
console.log(triple(5));

Fixed Code

function memoize(fn) {
  const cache = {};
  return function(...args) {
    const key = JSON.stringify(args);
    if (key in cache) return cache[key];
    cache[key] = fn(...args);
    return cache[key];
  };
}

const double = memoize(x => x * 2);
const triple = memoize(x => x * 3);

double(5);
console.log(triple(5));

Bug Explained

Bug: cache is declared outside memoize — all memoized functions share one global cache. double(5)=10 is stored under key "[5]". triple(5) finds "[5]" and returns 10.

Explanation: Moving cache inside memoize gives each memoized function its own private cache via closure.

Key Insight: State inside a factory function is private to each returned function — this is the closure encapsulation pattern.

More Closures & Scope Debug Challenges

Easyvar in loop — all closures share one variableMediumCounter factory shares global stateEasyWallet exposes stale primitive snapshotHardDefault parameter creates new function every call

Practice spotting bugs live →

38 debug challenges with AI hints

🐛 Try Debug Lab