title: Why does JavaScript not throw an exception for this code sample?
body: <p>I hope people will forgive me a fairly basic JavaScript question (it's not generally a "primary" language for me). I was looking at W3Schools's JavaScript tutorial for review; their <a href="https://www.w3schools.com/js/js_arrays.asp" rel="nofollow noreferrer">lesson on arrays</a> has the following warning and code sample:</p>
  
  <blockquote>
    <p>Warning: Adding elements with high indexes can create undefined "holes" in an array:</p>
  </blockquote>
  
  <pre><code>var fruits = ["Banana", "Orange", "Apple", "Mango"];
  fruits[6] = "Lemon"; // adds a new element (Lemon) to fruits
  </code></pre>
  
  <p>This will result in indices 4 and 5 containing <code>undefined</code>.</p>
  
  <p>Furthermore, I can do something like <code>alert(fruits[20]);</code> (which gives me a popup saying "undefined") without exception.</p>
  
  <p>In most languages that are more strict about typing, trying to do either of those actions would result in a runtime exception. I do realize that none of us on here were on the JavaScript design committee (as far as I know), but does anyone know why are these allowed (i.e. why don't they throw runtime exceptions or something like that)?</p>
  
  <p>I can understand the purpose of doing something like <code>fruits[4] = "Lemon"</code> (because that's essentially appending to the array), but is there ever a valid reason to do something like <code>fruits[6] = "Lemon"</code>?</p>
  
  <p>It also seems like doing something like <code>alert(fruits[20]);</code> would <em>almost always</em> indicate a bug - I can't think of any legitimate use case for it actually. Is this correct?</p>
  
  <p>My understanding from the answers to <a href="https://stackoverflow.com/questions/7069250/are-javascript-arrays-actually-linked-lists">this question</a> is that JavaScript arrays "are actually more like custom objects that use the properties as indexes" than they are like arrays in Java or C#. One of the answers also states</p>
  
  <blockquote>
    <p>Javascript arrays are not true arrays like in C/C++ or other languages. Therefore, they aren't as efficient, but they are arguably easier to use and do not throw out of bounds exceptions.</p>
  </blockquote>
  
  <p>Are these statements correct? Is this the reason for this behavior in JavaScript?</p>