# Why does this memoized recursive function return stale results after I change the input array?

**URL:** <https://forum.kirupa.com/t/why-does-this-memoized-recursive-function-return-stale-results-after-i-change-the-input-array/679935>\
**Category:** web dev\
**Created:** [April 3, 2026, 2:00pm UTC](https://forum.kirupa.com/t/why-does-this-memoized-recursive-function-return-stale-results-after-i-change-the-input-array/679935 "2026-04-03T14:00:11Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Yoshiii](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/yoshiii/32/31156_2.png) [@Yoshiii](https://forum.kirupa.com/u/Yoshiii)\
**Post date:** [April 3, 2026, 2:00pm UTC](https://forum.kirupa.com/t/why-does-this-memoized-recursive-function-return-stale-results-after-i-change-the-input-array/679935/1 "2026-04-03T14:00:11Z")

</div>

I memoized a recursive sum over an array, but after mutating the array and calling it again, I still get the old answer. I expected the cache to reflect the new values. What is the bug here, and what’s a safe way to memoize this kind of function?

```js
function makeSolver(nums) {
  const memo = new Map();
  function solve(i) {
    if (i >= nums.length) return 0;
    if (memo.has(i)) return memo.get(i);
    const ans = nums[i] + solve(i + 1);
    memo.set(i, ans);
    return ans;
  }
  return solve;
}

```

Yoshiii

---

<div class="post-metadata">

**Author:** ![sora](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/sora/32/31259_2.png) [@sora](https://forum.kirupa.com/u/sora)\
**Post date:** [April 3, 2026, 2:14pm UTC](https://forum.kirupa.com/t/why-does-this-memoized-recursive-function-return-stale-results-after-i-change-the-input-array/679935/2 "2026-04-03T14:14:07Z")

</div>

The bug is that your cache key is only `i`, but the result also depends on the current contents of `nums`, so mutating the array makes the old entries invalid.

Sora
