title: Javascript Map ordering
body: <p>i recently had a bug in my code that was due to me missing the "<em>in insertion order</em>" text while looking through Map object details on MDN. In short, i have a map object, lets say</p>
  
  <pre><code>let myMap = new Map;
  </code></pre>
  
  <p>and then, after populating it, i iterate over its contents with a simple <em>for .. of</em> statement. Like this</p>
  
  <pre><code>for (let [key, val] of myMap) { 
      ...
  }
  </code></pre>
  
  <p>The code in <em>for</em> loop depends on (key, value) pair to be sorted by <em>key</em>. However the algorithm that populates the map, does so in a random order(and i can't change that). To get around this problem, i now add all possible keys to the map object first, something like this:</p>
  
  <pre><code>let myMap = new Map;
  for (let i=0; i&lt;maxkey; ++i) myMap.set(key(i), undefined);
  
  // And in the for loop
  for (let [key, val] of myMap) {
      if (typeof val === "undefined") continue;
      //...
  }
  </code></pre>
  
  <p>Fortunately, there aren't many of them(so the performance penalty is negligible), and this works. Still this solution looks a bit awkward to me.</p>
  
  <p>Is there something better?</p>