Spot the bug - #17

There is one deliberate bug here.

const cache = new Map();

function getUser(id) {
  if (cache[id]) return cache[id];
  const user = { id, name: 'Ari' };
  cache[id] = user;
  return user;
}

Reply with what is broken and how you would fix it.

MechaPrime

Map doesn’t work with cache[id] — that’s just setting a random property on the object, so the “cache” check won’t behave like you think (and 0/empty ids get weird too). Use cache. has(id) + cache. get(id) and cache. set(id, user) instead.

Map keys are strict, so "1" and 1 become two different entries and you’ll “miss” the cache even though it looks populated.

I’ve been burned by this when one call site passed a route param (string) and another passed a numeric id, so I just normalize once up front (pick String or Number and stick to it) and then use has/get/set.

Hmm interesting

That if (cache[id]) check will bite you the second the cached value can be 0 or '' or false — it’ll act like a miss and redo the work.

Better to check “does this key exist” (has on a Map, or Object.hasOwn(cache, id) / id in cache for a plain object) so falsy values still count as cached.

cache[id] is a different bug when cache is a Map — that’s just property access on the Map object, not a lookup in the map.

So if an id happens to be "get"/"has" etc, you can accidentally read a method (a function) instead of your cached value. Using cache.has(id) + cache.get(id) avoids both the falsy-value problem and the “oops I grabbed a method” problem.

Bracket access on a Map isn’t a lookup — it’s just property access on the Map instance, so an id like "get"/"has" can literally give you the method function back. cache.has(id) + cache.get(id) keeps it a real map read and avoids the separate “falsy value means cache miss” bug from if (cache[id]) checks.