title: How does a JavaScript function store local variables after being called?
body: <p>I came upon this simplified example of a memoization function in JavaScript. It's then used to memoize a function that adds 2 to whatever number is passed in. When I saw this, it didn't seem obvious that the <code>memoize</code> function would continue to store the <code>cache</code> variable after being ran since it's not a property of <code>memoize</code>, just (seemingly) an ordinary local variable. Shouldn't it be overridden whenever <code>memoize</code> is called via <code>plusTwo</code>? Where can I find out more about this behavior in JavaScript?</p>
  
  <pre><code>var memoize = function(function_) {
      var cache = {};
  
      return function() { // What does this function do?
  
          //makes a string out of the arguments of the function that was passed in
          var arg_str = JSON.stringify(arguments);
  
          /* 
          sets the cache value for the arguments to the value that was already calculated 
          (if available) or calculates the value for the passed in function on its
          */
          cache[arg_str] = cache[arg_str] || function_.apply(function_, arguments);
  
          console.log(cache);
          // returns the calculated (or cached) value
          return cache[arg_str];
      };
  };
  
  var plusTwo = memoize(function (x) {
      return x + 2;
  });
  
  module.exports = memoize, plusTwo;
  </code></pre>