title: How to dynamically populate an array using a for in loop
body: <p>To return an array <code>set</code> with a sequence of random numbers between 1 and 500 I tried to refactor a standard for loop <code>for(var i = 0; i&lt; 50; i++)</code> and that worked but when I tried to do a refactor using a <code>for in</code> loop it doesn't. My guess is that there is something about the <code>array.length</code> property and it's use that I'm screwing up.</p>
  <p><strong>TL;DR</strong> Why does this return an array of 50 undefined elements rather than an array of 50 random integers? And is there a way to make this approach work?</p>
  <pre><code>var set = [];
  set.length = 50;
  
  for(var i in set){
      set[i] = Math.floor((Math.random() * 500) + 1);
  }
  
  console.log(set);
  </code></pre>
  <p><strong>Similar Questions:</strong> Helpful but not quite what I'm looking for</p>
  <ul>
  <li><a href="https://stackoverflow.com/questions/3010840/loop-through-array-in-javascript">Loop through an array in JavaScript</a></li>
  <li><a href="https://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea">Why is using &quot;for...in&quot; with array iteration a bad idea?</a></li>
  </ul>
  <h1>Update</h1>
  <p>As I suspected the point I was missing is that setting <code>set.length</code> doesn't add elements to the array it only creates a sparse array (an array with gaps). In my case you cannot use <code>for in</code> because there isn't anything <em>in</em> the array to iterate over. I would either have to populate the array with dummy content(i.e. empty strings) or, more logically, separate the range part I tried to implement with the <code>.length</code> property into a separate <code>range</code> variable.</p>
  <p><strong>Working version</strong></p>
  <pre><code>var set = [], range = 50;
  
  for(var i = 0; i &lt; range; i++){
      set[i]=Math.floor((Math.random() * 500) + 1);
  }
  
  console.log(set);
  </code></pre>