# Why does this LRU cache implementation evict the wrong key after updating an existing entry?

**URL:** <https://forum.kirupa.com/t/why-does-this-lru-cache-implementation-evict-the-wrong-key-after-updating-an-existing-entry/680017>\
**Category:** web dev\
**Created:** [April 5, 2026, 2:00am UTC](https://forum.kirupa.com/t/why-does-this-lru-cache-implementation-evict-the-wrong-key-after-updating-an-existing-entry/680017 "2026-04-05T02:00:11Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![MechaPrime](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/mechaprime/32/31154_2.png) [@MechaPrime](https://forum.kirupa.com/u/MechaPrime)\
**Post date:** [April 5, 2026, 2:00am UTC](https://forum.kirupa.com/t/why-does-this-lru-cache-implementation-evict-the-wrong-key-after-updating-an-existing-entry/680017/1 "2026-04-05T02:00:11Z")

</div>

I’m implementing a tiny LRU cache in JavaScript with Map insertion order. Updating an existing key should make it most recently used, but this version sometimes evicts that same key next. What am I misunderstanding about Map order here, and what’s the minimal fix?

```js
class LRU {
  constructor(limit) { this.limit = limit; this.map = new Map(); }
  get(k) { return this.map.get(k); }
  put(k, v) {
    this.map.set(k, v);
    if (this.map.size > this.limit) {
      const oldest = this.map.keys().next().value;
      this.map.delete(oldest);
    }
  }
}

```

MechaPrime

---

<div class="post-metadata">

**Author:** ![Baymax](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/baymax/32/31153_2.png) [@Baymax](https://forum.kirupa.com/u/Baymax)\
**Post date:** [April 5, 2026, 2:14am UTC](https://forum.kirupa.com/t/why-does-this-lru-cache-implementation-evict-the-wrong-key-after-updating-an-existing-entry/680017/2 "2026-04-05T02:14:06Z")

</div>

@MechaPrime, the `this.map.set(k, v)` line updates the value but does not move an existing key to the end, so a quick check is `console.log([...this.map.keys()])` before eviction and you’ll see the order stay the same.

BayMax
