πŸ”΄ HardFix the CodeπŸ› Debug Challenge

WeakMap key stored as primitive β€” cannot be set

Buggy Code β€” Can you spot the issue?

const userCache = new WeakMap();

function cacheUserData(userId, data) {
  // userId is a number β€” WeakMap keys must be objects!
  userCache.set(userId, data); // TypeError!
  return data;
}

function getUserData(userId) {
  return userCache.get(userId);
}

cacheUserData(42, { name: 'Alice' });

Fixed Code

// Option 1: Use a regular Map (if userId is a primitive)
const userCache = new Map();

function cacheUserData(userId, data) {
  userCache.set(userId, data); // βœ… Map accepts any key type
  return data;
}

// Option 2: Use WeakMap keyed by the user OBJECT (not its ID)
const userObjCache = new WeakMap();

function cacheUser(userObj, computedData) {
  userObjCache.set(userObj, computedData); // userObj is an object βœ“
  return computedData;
}

// Option 3: If you need number IDs and auto-cleanup, wrap in an object
const keyRegistry = new Map(); // id β†’ wrapper object
function getKey(id) {
  if (!keyRegistry.has(id)) keyRegistry.set(id, { id });
  return keyRegistry.get(id);
}
const cache = new WeakMap();
cache.set(getKey(42), { name: 'Alice' });

Bug Explained

Bug: WeakMap only accepts objects (or registered symbols) as keys. Primitives like numbers, strings, booleans throw TypeError.

Explanation: WeakMap requires object keys so it can hold weak references (GC can collect them). Primitives are not GC'd β€” they don't need weak references. Use Map for primitive keys.

Key Insight: WeakMap keys must be objects. For primitive keys (string, number), use a regular Map. Use WeakMap when the key is an object and you want automatic cleanup when the object is GC'd.

More Fix the Code Debug Challenges

🟒 EasyDeep clone breaks with JSON.stringifyβ†’πŸŸ‘ Mediumthis lost in event listenerβ†’πŸŸ‘ MediumObject mutation in array mapβ†’πŸ”΄ HardPrototype pollution vulnerabilityβ†’

Practice spotting bugs live β†’

38 debug challenges with AI hints

πŸ› Try Debug Lab