title: Node.js for() loop returning the same values at each loop
body: <p>I'm making this really simple application to help me explore nodejs and I have a particular handler that generates HTML code based on the top10 messages in my database. The snippet I'm having problem with loops through the messages and call the function generating HTML and appends the result to my html string.</p>
  
  <pre><code>function CreateMessageboard(BoardMessages){
    var htmlMessageboardString = "";
  
    [... Console debug code ...]
  
    for(var i = 0; i &lt; BoardMessages.length;i++){
          (function(){
              var j = i;
              console.log("Loading message %d".green, j);
              htmlMessageboardString += MessageToHTMLString(BoardMessages[j]);
            })();
    }
  }
  </code></pre>
  
  <p>I think my problem is due to either Javascript's way of handling loops, related to closures from what I read and this is what I tried using above or the async way nodejs handles my function. Right now the 10 results are well returned from the db but the last message is processed at every loop.</p>
  
  <p>I also tried, instead of doing var j = i, to take value i as function parameter and pass it in the closure and it returned the same results anyway. </p>
  
  <p>I have a feeling I'm missing critical knowledge to solve my problem, can I get light on this matter ?</p>
  
  <p>Edit : I'm welcome to give any other info on the code, I'd post the whole git repo but people probably don't want to swim through a whole project to help me debug this issue so I posted the whole function in the comments to provide more context.</p>