title: Array length and undefined indexes
body: <p>I just want to understand how Javascript arrays work but I have a complicated problem here.</p>
  
  <p>First I created my array:</p>
  
  <pre><code>var arr = [];
  </code></pre>
  
  <p>And set some elements in it:</p>
  
  <pre><code>arr[5] = "a thing";
  arr[2] = undefined;
  </code></pre>
  
  <p>I thought that I should have an array of size 2, because I only have two objects at 2 specific indexes. So I tested it with the <code>.length</code> property of arrays:</p>
  
  <pre><code>document.write(arr.length + "&lt;br&gt;");
  </code></pre>
  
  <p>The result, interestingly, is 6. But it must contain two items. How can its size be 6? It is probably related with the latest index that I used, here <code>arr[5] = "a thing";</code></p>
  
  <p>I then tried to loop over it:</p>
  
  <pre><code>var size = 0;
  for(var x in arr){
   size++;   
  }
  </code></pre>
  
  <p>And the <code>size</code> variable is now 2. So, what I learned from this: if I use a <code>for in</code> loop, I will calculate how many properties are in it, not its last index.</p>
  
  <p>But if I try to <code>document.write(arr[4])</code> (which is not set yet), it writes <code>undefined</code>.</p>
  
  <p>So why is <code>arr[2]</code> counted in the <code>for..in</code> loop, but not <code>arr[4]</code>?</p>
  
  <p>Let me answer my question: what I was thinking about <code>typeof undefined == undefined</code> which is amazingly true. But this is JavaScript, we need to play with it using his own rules :)</p>
  
  <p><a href="http://jsfiddle.net/0fy346pe/" rel="nofollow noreferrer">jsFiddle</a> and snippet below.</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var arr = [];
  
  arr[5] = "a thing";
  arr[2] = undefined;
  document.write(arr.length + "&lt;br&gt;");
  
  var size = 0;
  for(var x in arr){
   size++;   
  }
  
  document.write(size + "&lt;br&gt;");
  
  document.write(arr[4] + "&lt;br&gt;");</code></pre>
  </div>
  </div>
  </p>