0

I'm trying to understand this memoized / recursive version of fibonacci -

 function fib(n, memo = {}) {
    if (n in memo) return memo[n];
    if (n === 1 || n === 2) return 1;

    memo[n] = fib(n - 1, memo) + fib(n - 2, memo); 
    return memo[n]
 }

What I don't understand is how the information saved to a local memo object from inner recursive calls / scopes can be accessed by outer scopes. I.e. if a function calls itself, and then saves some info to the memo, how can the memo object in the higher scope (from where the recursive call was made) be updated if the update was made in a different scope?

When calling a function inside of another function, the former function doesn't have access to the latter function's local variables. When a function is called recursively, I like to think of it as though a function is calling a completely different function. This way of thinking has been helpful, but perhaps in this case it's misleading / wrong.

Thanks for the help in advance frens!

DC1477
  • 311
  • 6
  • 13
  • 1
    Only one "memo" object exists throughout all recursive calls given a single outer call of `fib` - right here `memo = {}`. That same exact object is then passed down to each recursive call as the second argument, and populated in the child functions - and since it's the same object, each such function sees the same populated values – CertainPerformance Jun 09 '22 at 03:17
  • 1
    While I agree that the linked question answers this well, and therefore agree with closing this question in favor of that one, I do want to point out that it is a well-written question! – Scott Sauyet Jun 13 '22 at 12:13

0 Answers0