title: A curious case of closure. Can anyone explain how this works?
body: <p>I stumbled upon this solution to a problem I had by using a closure, but I have no idea why it actually works, and why my original code did not.</p>
  
  <p>I have a helper function that takes a default_object. It returns another function that takes some object and uses it to fill in values for the default object:</p>
  
  <pre><code>function DTO(default_object){
      return function (object) {
  
          var dto = default_object;
  
          for (key in default_object) {
              if (key in object) {
                  dto[key] = object[key];
              }
          }
          return dto;
      }
  }
  </code></pre>
  
  <p>I then use this function like so:</p>
  
  <pre><code>var user = function(object) {
          return DTO({
              name: null,
              color: "#ffffff",
              public_id: null,
          })(object);
      }
  
  var clean_users = []
  unclean_users.forEach(function(unclean_user){
      clean_users.push(user(unclean_user));
  });
  </code></pre>
  
  <p>Which returns an array of safe user objects.
  Originally I had:</p>
  
  <pre><code>var user = DTO({
              name: null,
              color: "#ffffff",
              public_id: null,
          });
      }
  </code></pre>
  
  <p>Which I assumed would perform the same way because DTO returns a function, but this makes clean_users filled with the same user (the first one) over and over again.</p>
  
  <p>I was under the impression that executing user in the loop would create a new function taking a new unclean_user as an argument each time and returning a new clean_user, but for some reason it only happens once.
  Can anyone explain why?</p>