title: Understanding a memoized Fibonacci function
body: <p>The function, taken from <a href="https://scotch.io/tutorials/understanding-memoization-in-javascript" rel="nofollow noreferrer">here</a>:</p>
  <pre><code>function fib(n,memo) {
     memo = memo || {}
     if (memo[n]) {
        return memo[n]
     }
     if (n &lt;= 1) {
        return 1
     }
     return memo[n] = fib(n - 1, memo) + fib(n - 2, memo)
  }
  </code></pre>
  <p>This is a working memoized recursive function that takes parameter n and returns the n:th Fibonacci number.</p>
  <p>What I fail to grasp is that how can the memo object with assigned values be visible across different recursive function calls? Here's a picture that I assume to be a correct depiction of what happens when the function is called with parameter 4, but please correct me if it's not:</p>
  <p><a href="https://i.stack.imgur.com/GDfq3.png" rel="nofollow noreferrer">Recursion chart</a></p>
  <p>Take a note of the function calls marked with 1. and 2. and their respective comments in the picture. How is it that number 2 (fib(1)) gets supplied a memo parameter that contains the value assigned in number 1 (fib(2))? Shouldn't the memo supplied to number 2 (fib(1)) be the same that was supplied to the fib(3) call above it, which would be an empty object?</p>
  <p>I know that the memo object could just be a global variable and all assignments to it would automatically be visible in all the recursions, but I'm just trying wrap my head around how this particular technique works.</p>
  <p>Hopefully this description made sense. Thank you.</p>